{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "c001",
   "metadata": {},
   "source": [
    "# Asking a Service for Data: an API and JSON"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c002",
   "metadata": {},
   "source": [
    "In this lesson we learn what an API is, how a program asks one for data with parameters and a user agent, how it checks the status code, and how it reads an answer in JSON: nested dictionaries and lists, and a key that is missing.\n",
    "\n",
    "## A summary and a count of links for a hardware term\n",
    "\n",
    "Suppose we want a study glossary of hardware terms: for each term, one short summary and a count of the links of its page. The count turns out to need care, because the service sends a long list of links in parts. A page of Wikipedia is made for a reader: next to the text it has a table of facts, numbers of references in square brackets and menus, and [Beautiful Soup](https://dvirross.com/courses/intro-data-science/data-collection-beautifulsoup) would cut each of them away, one part at a time. Wikipedia offers another way: an **[API](https://dvirross.com/courses/intro-data-science/glossary#api)** (application programming interface), a way that a service offers to programs to ask for data. A page is written for a person, with tags and layout; an API answers a program with the data itself, in a format that a program reads without cutting anything out.\n",
    "\n",
    "The English Wikipedia answers such questions at one address, `https://en.wikipedia.org/w/api.php`, and its rules are in the [documentation of the API](https://www.mediawiki.org/wiki/API:Main_page). Every service writes its own rules: which questions it answers, how a question is written, and what the answer looks like."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c003",
   "metadata": {},
   "source": [
    "## Setup: the libraries and the check function\n",
    "\n",
    "No account and no key are needed. The next cell imports `requests` (Colab has it; the cell installs it if the session does not). The answers that the code reads are saved copies of real answers of the English Wikipedia API, kept on the public site of the course, so the numbers are the same for everyone. The cell marked **Live service** calls Wikipedia itself, so its numbers can differ from the page, and it can fail when the service does not answer or asks to slow down. It is switched off (`RUN_LIVE = False`), so that a whole class does not send requests to Wikipedia from one address at once."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "c004",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T03:33:54.979180Z",
     "iopub.status.busy": "2026-11-22T03:33:54.979015Z",
     "iopub.status.idle": "2026-11-22T03:33:54.984511Z",
     "shell.execute_reply": "2026-11-22T03:33:54.983414Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "requests 2.34.2\n"
     ]
    }
   ],
   "source": [
    "try:\n",
    "    import requests\n",
    "except ImportError:\n",
    "    !pip install -q requests\n",
    "    import requests\n",
    "print('requests', requests.__version__)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c005",
   "metadata": {},
   "source": [
    "The next cell defines the function `check(task_number)`. After you run the cell of a task, run the cell under it: `check` runs your cell again, collects what it prints, and compares it with the expected output. It tells you whether the output is right, and where it differs if not; it never shows the solution."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "c006",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T03:33:54.985843Z",
     "iopub.status.busy": "2026-11-22T03:33:54.985702Z",
     "iopub.status.idle": "2026-11-22T03:33:54.993712Z",
     "shell.execute_reply": "2026-11-22T03:33:54.992632Z"
    }
   },
   "outputs": [],
   "source": [
    "import ast, contextlib, hashlib, io\n",
    "\n",
    "# The expected output of each task, as hashes of its lines (the solutions are not stored here).\n",
    "EXPECTED = {int(k): v for k, v in {\n",
    "    '1': [\n",
    "        '6098f90d6d7f'\n",
    "    ],\n",
    "    '2': [\n",
    "        'e8df814b551f'\n",
    "    ],\n",
    "    '3': [\n",
    "        'b17ef6d19c7a'\n",
    "    ],\n",
    "    '4': [\n",
    "        'e16aa6ff26b8',\n",
    "        '2ea60c2384a6'\n",
    "    ]\n",
    "}.items()}\n",
    "\n",
    "\n",
    "def check(task):\n",
    "    \"\"\"Run the last cell that ran (not a check) again and compare what it prints with the expected output of the task.\"\"\"\n",
    "    if task not in EXPECTED:\n",
    "        print('There is no such task: ', task)\n",
    "        return\n",
    "    cells = [s for s in In[:-1] if s.strip() and not s.lstrip().startswith('check(')]   # In: the cells that ran, kept by IPython\n",
    "    tree = ast.parse(cells[-1] if cells else '')\n",
    "    last = tree.body.pop() if tree.body and isinstance(tree.body[-1], ast.Expr) else None   # a bare last expression counts as printed\n",
    "    out = io.StringIO()\n",
    "    try:\n",
    "        with contextlib.redirect_stdout(out):\n",
    "            exec(compile(tree, '<task>', 'exec'), globals())\n",
    "            if last is not None:\n",
    "                value = eval(compile(ast.Expression(last.value), '<task>', 'eval'), globals())\n",
    "                if value is not None:\n",
    "                    print(repr(value))\n",
    "    except Exception as error:\n",
    "        print('The cell raised an error:', type(error).__name__ + ':', error)\n",
    "        return\n",
    "    got = [hashlib.sha256(line.rstrip().encode()).hexdigest()[:12] for line in out.getvalue().rstrip().splitlines()]\n",
    "    want = EXPECTED[task]\n",
    "    if not got:\n",
    "        print('Nothing was printed. Print the answer in the task cell, run it, and run `check` straight after it.')\n",
    "    elif len(got) != len(want):\n",
    "        print('The cell printed {got} line(s) and the task expects {want}. Re-read the task and the hint.'.format(got=len(got), want=len(want)))\n",
    "    elif got != want:\n",
    "        print('Line {k} is different from the expected output. Re-read the task and the hint.'.format(k=next(i for i in range(len(want)) if got[i] != want[i]) + 1))\n",
    "    else:\n",
    "        print('OK: the output is as expected.')\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c007",
   "metadata": {},
   "source": [
    "## Saved answers of the real service\n",
    "\n",
    "The security settings of this site let its pages call only this site, so the boxes of this page cannot call Wikipedia. The answers were asked from the real service once, on 16 November 2026, and saved unchanged as six files on this site. Each file holds the answer to one question, so the parameters that we write in the boxes do not change it. On the real service the call is the same, with the address `https://en.wikipedia.org/w/api.php` and the same parameters. The notebooks run the same code on the saved copies; their cell for the real service is off (`RUN_LIVE = False`), because a class shares one address and the service asks programs to send few requests.\n",
    "\n",
    "The text of Wikipedia is available under the [Creative Commons Attribution-ShareAlike 4.0 license](https://creativecommons.org/licenses/by-sa/4.0/) (CC BY-SA 4.0). The titles, summaries, lists of links and sizes of pages in the saved answers are from the English Wikipedia, [en.wikipedia.org](https://en.wikipedia.org), retrieved on 16 November 2026 through its API; their authors are the editors of Wikipedia, whom the history of each page lists. The files are unchanged, and a text that is taken from them must keep this attribution and the same license.\n",
    "\n",
    "## An endpoint and its parameters\n",
    "\n",
    "The address to which a program sends its questions is an **[endpoint](https://dvirross.com/courses/intro-data-science/glossary#endpoint)**. A question is written as **[query parameters](https://dvirross.com/courses/intro-data-science/glossary#query-parameter)**: pairs of a name and a value that are added to the address after a `?` and separated by `&`. The function `requests.get` takes the parameters as a dictionary in its argument `params`, and builds the final address from them. In the first question the parameters ask for the introduction of the page of the field-programmable gate array. The attribute `url` of the response is the address that was sent, and `split('?')[1]` keeps the text after the question mark.\n",
    "\n",
    "## What the parameters say\n",
    "\n",
    "| Parameter | Value | Meaning |\n",
    "| --- | --- | --- |\n",
    "| `action` | `query` | Ask for data about pages |\n",
    "| `format` | `json` | Write the answer in JSON |\n",
    "| `formatversion` | `2` | The newer, simpler layout of the answer |\n",
    "| `prop` | `extracts` | The property of the page that we want: a text extract |\n",
    "| `exintro` | `1` | Only the introduction, the text before the first heading |\n",
    "| `explaintext` | `1` | Plain text, without tags |\n",
    "| `titles` | `Field-programmable gate array` | The title of the page |\n",
    "\n",
    "The box below sends the question of the table to the saved copy and prints the part of the address after the `?`, as the library wrote it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "c008",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T03:33:54.995517Z",
     "iopub.status.busy": "2026-11-22T03:33:54.995338Z",
     "iopub.status.idle": "2026-11-22T03:33:55.000998Z",
     "shell.execute_reply": "2026-11-22T03:33:55.000089Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "action=query&format=json&formatversion=2&prop=extracts&exintro=1&explaintext=1&titles=Field-programmable+gate+array\n"
     ]
    }
   ],
   "source": [
    "import requests\n",
    "\n",
    "copies = (\n",
    "    'https://dvirross.com/materials/courses/'\n",
    "    'intro-data-science/'\n",
    ")\n",
    "summary_params = {\n",
    "    'action': 'query', 'format': 'json', 'formatversion': 2,\n",
    "    'prop': 'extracts', 'exintro': 1, 'explaintext': 1,\n",
    "    'titles': 'Field-programmable gate array',\n",
    "}\n",
    "response = requests.get(\n",
    "    copies + 'wikipedia-fpga-summary.json',\n",
    "    params=summary_params,\n",
    ")\n",
    "print(response.url.split('?')[1])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c009",
   "metadata": {},
   "source": [
    "The library wrote each pair as `name=value` and replaced the spaces of the title with `+`, because an address has no spaces.\n",
    "\n",
    "On the real service the same question is a call to the endpoint of Wikipedia. It is shown here and not run, because the boxes of this page cannot reach it:\n",
    "\n",
    "```python\n",
    "response = requests.get(\n",
    "    'https://en.wikipedia.org/w/api.php',\n",
    "    params=summary_params,\n",
    ")\n",
    "```\n",
    "\n",
    "The final address that `requests` sends is the endpoint, a `?` and the parameters, all on one line. The same address in the address bar of a browser shows the answer as text.\n",
    "\n",
    "```text\n",
    "https://en.wikipedia.org/w/api.php?action=query&format=json&formatversion=2&prop=extracts&exintro=1&explaintext=1&titles=Field-programmable+gate+array\n",
    "```\n",
    "\n",
    "## The status code\n",
    "\n",
    "Every answer of a server starts with a **[status code](https://dvirross.com/courses/intro-data-science/glossary#status-code)**, which a program checks before it reads the rest. The attribute `status_code` of the response holds it. A request for a file that does not exist on this site returns a response with the code 404."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "c010",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T03:33:55.002828Z",
     "iopub.status.busy": "2026-11-22T03:33:55.002673Z",
     "iopub.status.idle": "2026-11-22T03:33:55.007179Z",
     "shell.execute_reply": "2026-11-22T03:33:55.006214Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "200\n",
      "404\n"
     ]
    }
   ],
   "source": [
    "print(response.status_code)\n",
    "\n",
    "missing = requests.get(copies + 'wikipedia-no-such-copy.json')\n",
    "print(missing.status_code)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c011",
   "metadata": {},
   "source": [
    "The common codes that a program meets in an API are these:\n",
    "\n",
    "| Code | Meaning and what the program does |\n",
    "| --- | --- |\n",
    "| 200 | The answer arrived: read it |\n",
    "| 403 | The service refuses: check the user agent and the rules |\n",
    "| 404 | There is no such address: check the endpoint |\n",
    "| 429 | Too many requests: wait before asking again; the answer may say for how long |\n",
    "\n",
    "A program that does not check the code reads an error message as if it were data. It checks with `if response.status_code != 200:` (`!=` means \"is not equal to\") and stops with a message.\n",
    "\n",
    "## Headers and the user agent\n",
    "\n",
    "A request carries, besides the parameters, **[headers](https://dvirross.com/courses/intro-data-science/glossary#header)**: pieces of information about the request itself, given to `requests.get` as a dictionary in the argument `headers`. The header that names the sender is `User-Agent`, the name of the program that sends the request, the **[user agent](https://dvirross.com/courses/intro-data-science/glossary#user-agent)**. The library sends `python-requests` unless we write another name, and the Wikimedia Foundation, which runs Wikipedia, asks in its [user-agent policy](https://foundation.wikimedia.org/wiki/Policy:Wikimedia_Foundation_User-Agent_Policy) for a name that says what the program is and how to reach its owner. The argument `timeout` is the number of seconds to wait for an answer before giving up; without it a program can wait forever."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "c012",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T03:33:55.008701Z",
     "iopub.status.busy": "2026-11-22T03:33:55.008560Z",
     "iopub.status.idle": "2026-11-22T03:33:55.013211Z",
     "shell.execute_reply": "2026-11-22T03:33:55.012211Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The answer arrived\n"
     ]
    }
   ],
   "source": [
    "headers = {\n",
    "    'User-Agent': (\n",
    "        'IntroDataScienceCourse/1.0 '\n",
    "        '(teaching example; contact via dvirross.com)'\n",
    "    )\n",
    "}\n",
    "response = requests.get(\n",
    "    copies + 'wikipedia-fpga-summary.json',\n",
    "    params=summary_params,\n",
    "    headers=headers,\n",
    "    timeout=30,\n",
    ")\n",
    "if response.status_code != 200:\n",
    "    print('The service answered', response.status_code)\n",
    "else:\n",
    "    print('The answer arrived')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c013",
   "metadata": {},
   "source": [
    "The saved copy does not read the header; the real service does. A polite program also asks few questions, one at a time, and keeps the answers, as the saved copies of this lesson do, instead of asking again.\n",
    "\n",
    "## The answer is JSON\n",
    "\n",
    "The answer of the API is text in a format called **[JSON](https://dvirross.com/courses/intro-data-science/glossary#json)** (JavaScript Object Notation). It is written with curly brackets that hold names and values, and square brackets that hold lists, dictionaries and lists like those of Python, with `true`, `false` and `null` in place of `True`, `False` and `None`. The text of the answer is `response.text`, a string.\n",
    "\n",
    "The method `json()` of the response reads the text and returns Python values: a dictionary for the curly brackets, a list for the square brackets, and text, numbers, `True` and `None` for the rest. The function `type` tells the type of a value, and a dictionary has a method `keys()` that returns its keys, the names, which `list` turns into a list."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "c014",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T03:33:55.014629Z",
     "iopub.status.busy": "2026-11-22T03:33:55.014480Z",
     "iopub.status.idle": "2026-11-22T03:33:55.017814Z",
     "shell.execute_reply": "2026-11-22T03:33:55.016854Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'str'> <class 'dict'>\n",
      "['batchcomplete', 'query']\n"
     ]
    }
   ],
   "source": [
    "data = response.json()\n",
    "print(type(response.text), type(data))\n",
    "print(list(data.keys()))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c015",
   "metadata": {},
   "source": [
    "## Dictionaries and lists, one inside the other\n",
    "\n",
    "The answer is a dictionary that holds a dictionary, which holds a list of dictionaries. Here is the whole answer with the long text of the extract cut short:\n",
    "\n",
    "```json\n",
    "{\n",
    "  \"batchcomplete\": true,\n",
    "  \"query\": {\n",
    "    \"pages\": [\n",
    "      {\n",
    "        \"pageid\": 10969,\n",
    "        \"ns\": 0,\n",
    "        \"title\": \"Field-programmable gate array\",\n",
    "        \"extract\": \"A field-programmable gate array (FPGA) is a type of ...\"\n",
    "      }\n",
    "    ]\n",
    "  }\n",
    "}\n",
    "```\n",
    "\n",
    "A value in the middle is reached one step at a time, with square brackets: a key for a dictionary, and for a list the **index**, the place of the item, counted from 0. `data['query']` is a dictionary; `['pages']` in it is a list with one item for each title that we asked about; `[0]` is its first item, a dictionary of one page; and `['title']` and `['extract']` are its values. The method `split('. ')` cuts a text at every period that is followed by a space, so `[0]` of its result is the first sentence."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "c016",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T03:33:55.019158Z",
     "iopub.status.busy": "2026-11-22T03:33:55.019012Z",
     "iopub.status.idle": "2026-11-22T03:33:55.022463Z",
     "shell.execute_reply": "2026-11-22T03:33:55.021509Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'list'> 1\n",
      "Field-programmable gate array\n",
      "1951\n",
      "A field-programmable gate array (FPGA) is a type of configurable integrated circuit that can be repeatedly programmed after manufacturing\n"
     ]
    }
   ],
   "source": [
    "pages = data['query']['pages']\n",
    "print(type(pages), len(pages))\n",
    "\n",
    "page = pages[0]\n",
    "print(page['title'])\n",
    "print(len(page['extract']))\n",
    "print(page['extract'].split('. ')[0])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c017",
   "metadata": {},
   "source": [
    "The summary of the page is 1,951 characters, and its first sentence says what an FPGA is. The program did not cut anything out of tags: it walked down the structure by names and places.\n",
    "\n",
    "### Practice\n",
    "\n",
    "**Your turn.** The variable `data` holds the answer about the field-programmable gate array. Print the length of the summary of the page in characters and, after a space, the number of its words: the number of words that `split()` finds in the `extract`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c018",
   "metadata": {},
   "source": [
    "> **Hint**\n",
    ">\n",
    "> Walk down the answer as in the box above, to the `extract` of the first page. The method `split()` without an argument cuts a text at its spaces and line breaks and returns a list of its words, and `len` counts a list."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c019",
   "metadata": {},
   "source": [
    "**Solution**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "c020",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T03:33:55.023949Z",
     "iopub.status.busy": "2026-11-22T03:33:55.023794Z",
     "iopub.status.idle": "2026-11-22T03:33:55.027064Z",
     "shell.execute_reply": "2026-11-22T03:33:55.026130Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1951 284\n"
     ]
    }
   ],
   "source": [
    "text = data['query']['pages'][0]['extract']\n",
    "print(len(text), len(text.split()))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c021",
   "metadata": {},
   "source": [
    "**Expected output**\n",
    "\n",
    "```text\n",
    "1951 284\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "c022",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T03:33:55.028417Z",
     "iopub.status.busy": "2026-11-22T03:33:55.028275Z",
     "iopub.status.idle": "2026-11-22T03:33:55.031346Z",
     "shell.execute_reply": "2026-11-22T03:33:55.030467Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "OK: the output is as expected.\n"
     ]
    }
   ],
   "source": [
    "check(1)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c023",
   "metadata": {},
   "source": [
    "**Common mistake**\n",
    "\n",
    "```python\n",
    "text = data['query']['pages'][0]['extract']\n",
    "print(len(text), len(text.split('. ')))\n",
    "```\n",
    "\n",
    "The argument `'. '` cuts the text at the end of each sentence, so the second number, 8, is the number of sentences and not the number of words."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c024",
   "metadata": {},
   "source": [
    "> **Self-study, importance 1.** This part is for self-study: it is not taught in the lecture, and you read it on your own. Several titles in one question and the order of the answer. It helps with: asking a service about several items at once and finding the largest and the smallest by a key."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c025",
   "metadata": {},
   "source": [
    "## Several pages in one question\n",
    "\n",
    "The parameter `titles` takes several titles, separated by `|`. The property `info` returns facts about a page, such as `length`, the size of its source text in bytes. The answer holds a list with one dictionary for each page, and a `for` loop goes over it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "c026",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T03:33:55.032581Z",
     "iopub.status.busy": "2026-11-22T03:33:55.032452Z",
     "iopub.status.idle": "2026-11-22T03:33:55.036911Z",
     "shell.execute_reply": "2026-11-22T03:33:55.035983Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Field-programmable gate array 68061\n",
      "Hardware description language 36937\n",
      "RISC-V 170750\n"
     ]
    }
   ],
   "source": [
    "info_params = {\n",
    "    'action': 'query', 'format': 'json', 'formatversion': 2,\n",
    "    'prop': 'info',\n",
    "    'titles': (\n",
    "        'RISC-V|Hardware description language|'\n",
    "        'Field-programmable gate array'\n",
    "    ),\n",
    "}\n",
    "info = requests.get(\n",
    "    copies + 'wikipedia-pages-info.json',\n",
    "    params=info_params,\n",
    ").json()\n",
    "info_pages = info['query']['pages']\n",
    "for page in info_pages:\n",
    "    print(page['title'], page['length'])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c027",
   "metadata": {},
   "source": [
    "The pages are not in the order of the question: the service returns them in its own order, here alphabetical. So a program finds a page by its title and not by its place in the list.\n",
    "\n",
    "**Your turn.** The list `info_pages` holds a dictionary for each of the three pages. Find the longest page and the shortest page by `length`, and print the title of the longest page and, after a space, how many times it is longer than the shortest page, rounded to one digit after the decimal point."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c028",
   "metadata": {},
   "source": [
    "> **Hint**\n",
    ">\n",
    "> The function `max` returns the item with the largest value, and its argument `key` says what to compare: `max(info_pages, key=lambda page: page['length'])`, where `lambda page: page['length']` is a small function that takes a page and returns its length. The function `min` works the same way."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c029",
   "metadata": {},
   "source": [
    "**Solution**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "c030",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T03:33:55.038069Z",
     "iopub.status.busy": "2026-11-22T03:33:55.037942Z",
     "iopub.status.idle": "2026-11-22T03:33:55.040933Z",
     "shell.execute_reply": "2026-11-22T03:33:55.040021Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "RISC-V 4.6\n"
     ]
    }
   ],
   "source": [
    "longest = max(info_pages, key=lambda page: page['length'])\n",
    "shortest = min(info_pages, key=lambda page: page['length'])\n",
    "ratio = longest['length'] / shortest['length']\n",
    "print(longest['title'], round(ratio, 1))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c031",
   "metadata": {},
   "source": [
    "**Expected output**\n",
    "\n",
    "```text\n",
    "RISC-V 4.6\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "c032",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T03:33:55.042016Z",
     "iopub.status.busy": "2026-11-22T03:33:55.041894Z",
     "iopub.status.idle": "2026-11-22T03:33:55.044913Z",
     "shell.execute_reply": "2026-11-22T03:33:55.043935Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "OK: the output is as expected.\n"
     ]
    }
   ],
   "source": [
    "check(2)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c033",
   "metadata": {},
   "source": [
    "**Common mistake**\n",
    "\n",
    "```python\n",
    "longest = max(info_pages, key=lambda page: page['length'])\n",
    "shortest = min(info_pages, key=lambda page: page['length'])\n",
    "ratio = shortest['length'] / longest['length']\n",
    "print(longest['title'], round(ratio, 1))\n",
    "```\n",
    "\n",
    "The division is the other way round, so it says how large the shortest page is as a fraction of the longest, 0.2, and not how many times the longest is longer."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c034",
   "metadata": {},
   "source": [
    "## The links of a page\n",
    "\n",
    "The property `links` returns the pages that a page links to. The parameter `pllimit` is the largest number of links in one answer, and `max` asks for the largest that the service allows; `plnamespace` set to `0` keeps only links to articles, and not to pages of help or of discussion. The answer holds, in the page, a list `links`, and each link is a dictionary with a `title`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "c035",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T03:33:55.046298Z",
     "iopub.status.busy": "2026-11-22T03:33:55.046136Z",
     "iopub.status.idle": "2026-11-22T03:33:55.050935Z",
     "shell.execute_reply": "2026-11-22T03:33:55.049973Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "500\n",
      "{'ns': 0, 'title': '20-sim'}\n"
     ]
    }
   ],
   "source": [
    "links_params = {\n",
    "    'action': 'query', 'format': 'json', 'formatversion': 2,\n",
    "    'prop': 'links', 'pllimit': 'max', 'plnamespace': 0,\n",
    "    'titles': 'Field-programmable gate array',\n",
    "}\n",
    "links_data = requests.get(\n",
    "    copies + 'wikipedia-fpga-links.json',\n",
    "    params=links_params,\n",
    ").json()\n",
    "links = links_data['query']['pages'][0]['links']\n",
    "print(len(links))\n",
    "print(links[0])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c036",
   "metadata": {},
   "source": [
    "The answer has 500 links, and 500 is the limit of one answer for a program without special rights, not the number of links of the page. The answer says so itself: it has a key `continue`, which holds the place where the next answer would start. The operator `in` tests whether a key is in a dictionary."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "c037",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T03:33:55.052226Z",
     "iopub.status.busy": "2026-11-22T03:33:55.052103Z",
     "iopub.status.idle": "2026-11-22T03:33:55.055158Z",
     "shell.execute_reply": "2026-11-22T03:33:55.054074Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "10969|0|Power_engineering_software\n"
     ]
    }
   ],
   "source": [
    "print('continue' in links_data)\n",
    "print(links_data['continue']['plcontinue'])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c038",
   "metadata": {},
   "source": [
    "The links are ordered by their titles, and the next answer starts at \"Power engineering software\". So the number 500 describes the first part of the links, from the start of the alphabet to the letter P, and a program that reports \"the page has 500 links\" would be wrong. Asking for the rest is a repetition of the request with the value of `continue` added to its parameters.\n",
    "\n",
    "The method `lower()` returns a text in lowercase letters, and `in` also tests whether a text contains another one: `'logic' in 'Logic gate'` is `False`, because the capital letter is a different character, and `'logic' in 'Logic gate'.lower()` is `True`.\n",
    "\n",
    "**Your turn.** Among the links in `links`, how many have a title that contains the letters `logic`, with a capital letter or without? Print how many there are, as one number."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c039",
   "metadata": {},
   "source": [
    "> **Hint**\n",
    ">\n",
    "> Build a list with a list comprehension, `[link['title'] for link in links if ...]`, whose condition tests the lowercase title: `'logic' in link['title'].lower()`. Print the length of the list."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c040",
   "metadata": {},
   "source": [
    "**Solution**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "c041",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T03:33:55.057239Z",
     "iopub.status.busy": "2026-11-22T03:33:55.057071Z",
     "iopub.status.idle": "2026-11-22T03:33:55.060284Z",
     "shell.execute_reply": "2026-11-22T03:33:55.059358Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "16\n"
     ]
    }
   ],
   "source": [
    "with_logic = [link['title'] for link in links if 'logic' in link['title'].lower()]\n",
    "print(len(with_logic))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c042",
   "metadata": {},
   "source": [
    "**Expected output**\n",
    "\n",
    "```text\n",
    "16\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "c043",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T03:33:55.061936Z",
     "iopub.status.busy": "2026-11-22T03:33:55.061765Z",
     "iopub.status.idle": "2026-11-22T03:33:55.065148Z",
     "shell.execute_reply": "2026-11-22T03:33:55.064021Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "OK: the output is as expected.\n"
     ]
    }
   ],
   "source": [
    "check(3)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c044",
   "metadata": {},
   "source": [
    "The count is of the first 500 links of the page, since this is what the answer holds."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c045",
   "metadata": {},
   "source": [
    "**Common mistake**\n",
    "\n",
    "```python\n",
    "with_logic = [link['title'] for link in links if 'logic' in link['title']]\n",
    "print(len(with_logic))\n",
    "```\n",
    "\n",
    "The test `'logic' in link['title']` is case sensitive, so it misses titles such as `Logic gate` and `Logic block`, which have a capital letter, and counts only 10 of the 16."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c046",
   "metadata": {},
   "source": [
    "## A key that is missing\n",
    "\n",
    "Not every page that we ask about exists. The next question asks for the summaries of two titles: `RISC-V`, and `RISC-VI`, a title that no page has. For the missing title the service answers with an item that has the key `missing` and no key `extract`, and it comes first in the list."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "c047",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T03:33:55.066508Z",
     "iopub.status.busy": "2026-11-22T03:33:55.066343Z",
     "iopub.status.idle": "2026-11-22T03:33:55.070724Z",
     "shell.execute_reply": "2026-11-22T03:33:55.069911Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n",
      "{'ns': 0, 'title': 'RISC-VI', 'missing': True}\n"
     ]
    }
   ],
   "source": [
    "missing_params = {\n",
    "    'action': 'query', 'format': 'json', 'formatversion': 2,\n",
    "    'prop': 'extracts', 'exintro': 1, 'explaintext': 1,\n",
    "    'exlimit': 'max', 'titles': 'RISC-V|RISC-VI',\n",
    "}\n",
    "answer = requests.get(\n",
    "    copies + 'wikipedia-summary-missing.json',\n",
    "    params=missing_params,\n",
    ").json()\n",
    "missing_pages = answer['query']['pages']\n",
    "print(len(missing_pages))\n",
    "print(missing_pages[0])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c048",
   "metadata": {},
   "source": [
    "Reading a key that is not there with square brackets stops the program with a `KeyError`. This is what `missing_pages[0]['extract']` does, and a program that reads many pages stops at the first missing one:\n",
    "\n",
    "```text\n",
    "KeyError: 'extract'\n",
    "```\n",
    "\n",
    "The method `get` of a dictionary takes a key and a default value, and returns the default instead of an error when the key is missing. With one argument, `get('extract')`, the default is `None`. A default value of the right kind lets the rest of the program go on: an empty text `''` for a text."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "c049",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T03:33:55.072312Z",
     "iopub.status.busy": "2026-11-22T03:33:55.072150Z",
     "iopub.status.idle": "2026-11-22T03:33:55.075141Z",
     "shell.execute_reply": "2026-11-22T03:33:55.074467Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "RISC-VI | no such page\n",
      "RISC-V | RISC-V (pronounced \"risk-five\") is a free and open standard instruction set architecture (ISA) for computer CPUs\n"
     ]
    }
   ],
   "source": [
    "for page in missing_pages:\n",
    "    text = page.get('extract', 'no such page')\n",
    "    print(page['title'], '|', text.split('. ')[0])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c050",
   "metadata": {},
   "source": [
    "The same care is needed for a whole answer. A question that the service cannot answer, here an `action` that does not exist, gets the status code 200 as well, and the answer holds a key `error` instead of the key `query`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "c051",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T03:33:55.076798Z",
     "iopub.status.busy": "2026-11-22T03:33:55.076666Z",
     "iopub.status.idle": "2026-11-22T03:33:55.080942Z",
     "shell.execute_reply": "2026-11-22T03:33:55.079954Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "no query in the answer\n",
      "Unrecognized value for parameter \"action\": nonsense.\n"
     ]
    }
   ],
   "source": [
    "bad = requests.get(\n",
    "    copies + 'wikipedia-error.json',\n",
    "    params={'action': 'nonsense', 'format': 'json'},\n",
    ").json()\n",
    "print(bad.get('query', 'no query in the answer'))\n",
    "print(bad['error']['info'])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c052",
   "metadata": {},
   "source": [
    "A program that reads an API checks the status code first, and then checks that the answer has the key that it needs.\n",
    "\n",
    "**Your turn.** For each page in `missing_pages`, print its title and, after a space, the number of words of its summary: the number of words that `split()` finds in the extract. A page that has no summary has 0 words."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c053",
   "metadata": {},
   "source": [
    "> **Hint**\n",
    ">\n",
    "> Take the extract with `get` and the default `''`, an empty text, and split it: `len(page.get('extract', '').split())`. The method `split()` of an empty text returns an empty list, whose length is 0."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c054",
   "metadata": {},
   "source": [
    "**Solution**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "c055",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T03:33:55.082071Z",
     "iopub.status.busy": "2026-11-22T03:33:55.081954Z",
     "iopub.status.idle": "2026-11-22T03:33:55.085451Z",
     "shell.execute_reply": "2026-11-22T03:33:55.084525Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "RISC-VI 0\n",
      "RISC-V 176\n"
     ]
    }
   ],
   "source": [
    "for page in missing_pages:\n",
    "    words = page.get('extract', '').split()\n",
    "    print(page['title'], len(words))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c056",
   "metadata": {},
   "source": [
    "**Expected output**\n",
    "\n",
    "```text\n",
    "RISC-VI 0\n",
    "RISC-V 176\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "c057",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T03:33:55.086623Z",
     "iopub.status.busy": "2026-11-22T03:33:55.086499Z",
     "iopub.status.idle": "2026-11-22T03:33:55.089667Z",
     "shell.execute_reply": "2026-11-22T03:33:55.088696Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "OK: the output is as expected.\n"
     ]
    }
   ],
   "source": [
    "check(4)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c058",
   "metadata": {},
   "source": [
    "**Common mistake**\n",
    "\n",
    "```python\n",
    "for page in missing_pages:\n",
    "    words = page.get('extract', 'no such page').split()\n",
    "    print(page['title'], len(words))\n",
    "```\n",
    "\n",
    "The default `'no such page'` is a text of three words, so the missing page gets the number 3 and not 0. A default has to be a value that the next step can use and that stands for \"nothing\": for a text that is split into words, an empty text."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c059",
   "metadata": {},
   "source": [
    "> **Self-study, importance 2.** This part is for self-study: it is not taught in the lecture, and you read it on your own. A search question, repeating a request to get all the links of a page, and a Python package for the Wikipedia API. It helps with: reading search results, collecting the parts of an answer that comes in parts, and using a package that calls an API."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c060",
   "metadata": {},
   "source": [
    "## A search question\n",
    "\n",
    "The answer to a search is a list too. The parameter `list` set to `search` asks the service to search for the words of `srsearch`, and `srlimit` is the number of results in the answer. The answer has, besides the results, the number of all the hits, `totalhits`, inside the dictionary `searchinfo`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "c061",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T03:33:55.090859Z",
     "iopub.status.busy": "2026-11-22T03:33:55.090729Z",
     "iopub.status.idle": "2026-11-22T03:33:55.095295Z",
     "shell.execute_reply": "2026-11-22T03:33:55.094398Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "18047\n",
      "Hardware description language 3718\n",
      "VHDL 4278\n",
      "Altera Hardware Description Language 275\n",
      "Ruby (hardware description language) 267\n",
      "Verilog 4227\n"
     ]
    }
   ],
   "source": [
    "search_params = {\n",
    "    'action': 'query', 'format': 'json', 'formatversion': 2,\n",
    "    'list': 'search', 'srlimit': 5,\n",
    "    'srsearch': 'hardware description language',\n",
    "}\n",
    "search = requests.get(\n",
    "    copies + 'wikipedia-search-hdl.json',\n",
    "    params=search_params,\n",
    ").json()\n",
    "print(search['query']['searchinfo']['totalhits'])\n",
    "for hit in search['query']['search']:\n",
    "    print(hit['title'], hit['wordcount'])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c062",
   "metadata": {},
   "source": [
    "The answer holds the first five of the 18,047 pages that fit the words. Each hit also has a `snippet`, a piece of its text with the found words wrapped in HTML tags.\n",
    "\n",
    "## All the links of a page\n",
    "\n",
    "To get all the links of a page, the program repeats the request. An answer that has a key `continue` says where the next one starts: its values are added to the parameters of the next request, and the loop stops when an answer has none. The code is shown and not run, because the saved copy holds only the first answer. The call `{**links_params, **extra}` writes the pairs of two dictionaries into one new dictionary, and `time.sleep(1)` pauses for a second between requests, to stay polite.\n",
    "\n",
    "```python\n",
    "import time\n",
    "\n",
    "all_links = []\n",
    "extra = {}\n",
    "while True:\n",
    "    answer = requests.get(\n",
    "        'https://en.wikipedia.org/w/api.php',\n",
    "        params={**links_params, **extra},\n",
    "        headers=headers,\n",
    "        timeout=30,\n",
    "    ).json()\n",
    "    page = answer['query']['pages'][0]\n",
    "    all_links += [link['title'] for link in page.get('links', [])]\n",
    "    if 'continue' not in answer:\n",
    "        break\n",
    "    extra = answer['continue']\n",
    "    time.sleep(1)\n",
    "print(len(all_links))\n",
    "```\n",
    "\n",
    "The number of links of a page changes with every edit of the page, so a program that runs it gets the number of that day.\n",
    "\n",
    "## A package that asks for us\n",
    "\n",
    "Some services have a Python package that writes the requests for us. For Wikipedia it is `Wikipedia-API`, imported as `wikipediaapi`. The code is shown and not run, because it calls the service. The package builds the address, sends the user agent that we give it, and returns the page as an object with a summary and its links.\n",
    "\n",
    "```python\n",
    "import wikipediaapi\n",
    "\n",
    "wiki = wikipediaapi.Wikipedia(\n",
    "    user_agent=(\n",
    "        'IntroDataScienceCourse/1.0 '\n",
    "        '(teaching example; contact via dvirross.com)'\n",
    "    ),\n",
    "    language='en',\n",
    ")\n",
    "page = wiki.page('Field-programmable gate array')\n",
    "print(page.summary[:200])\n",
    "print(len(page.links))\n",
    "```\n",
    "\n",
    "A package is shorter, and it hides the parameters and the structure of the answer; a service that has no package is still within reach for a program that makes the call itself.\n",
    "\n",
    "## Keep in mind\n",
    "\n",
    "- An API is a way that a service offers for programs to ask for data; its answer is data, not a page to cut out of tags.\n",
    "- A question is an endpoint and query parameters: `requests.get(url, params={...})` writes the final address, with `name=value` pairs after a `?`.\n",
    "- `headers={'User-Agent': ...}` says who is asking, and `timeout` limits the wait. A polite program asks few questions, one at a time, and keeps the answers.\n",
    "- Check `response.status_code` first: 200 is an answer, and 429 means to wait. A service can also answer 200 with an error inside the JSON.\n",
    "- `response.json()` returns dictionaries and lists, and a value is reached with keys and indexes: `data['query']['pages'][0]['title']`.\n",
    "- An answer can be a part of the data: the key `continue` says that there is more, and a count of the answer is not a count of the page.\n",
    "- A missing key stops the program with `KeyError`; `get(key, default)` returns a default, and the default should be of the kind that the next step needs."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c063",
   "metadata": {},
   "source": [
    "**Live service.** The cell below can ask the English Wikipedia itself for the summary of the page on the field-programmable gate array, with a user agent that says how to reach us, a timeout, and a check of the status code. It is switched off (`RUN_LIVE = False`): a whole class that runs it together sends many requests from one address, and Wikipedia answers programs that send too many with the status code 429. One person, once, can set `RUN_LIVE = True` to see the real service. The rest of the notebook works on the saved copies."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "c064",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T03:33:55.096571Z",
     "iopub.status.busy": "2026-11-22T03:33:55.096386Z",
     "iopub.status.idle": "2026-11-22T03:33:55.099416Z",
     "shell.execute_reply": "2026-11-22T03:33:55.098481Z"
    }
   },
   "outputs": [],
   "source": [
    "RUN_LIVE = False  # switch to True to ask Wikipedia itself (one request)\n",
    "if RUN_LIVE:\n",
    "    live_headers = {'User-Agent': 'IntroDataScienceCourse/1.0 (teaching example; contact via dvirross.com)'}\n",
    "    live = requests.get('https://en.wikipedia.org/w/api.php', params=summary_params, headers=live_headers, timeout=30)\n",
    "    if live.status_code == 429:\n",
    "        print('Too many requests (status 429). Wait', live.headers.get('Retry-After', 'a while'), 'seconds, do not try again now, and use the saved copy.')\n",
    "    elif live.status_code != 200:\n",
    "        print('The service answered with status', live.status_code, '. Use the saved copy.')\n",
    "    else:\n",
    "        live_page = live.json()['query']['pages'][0]\n",
    "        print(live_page['title'], len(live_page['extract']))\n",
    "else:\n",
    "    print('The live cell is off. Set RUN_LIVE = True to run it.')"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.18"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
