{
 "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. We then see how a package does the same work for us.\n",
    "\n",
    "## A hardware glossary built from Wikipedia\n",
    "\n",
    "Suppose we want to build a study glossary of hardware terms from the information in Wikipedia: for each term we take the short summary of its page, and count how many other Wikipedia pages the page links to, that is, how many related terms it points to. 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-29T09:54:37.006479Z",
     "iopub.status.busy": "2026-11-29T09:54:37.006316Z",
     "iopub.status.idle": "2026-11-29T09:54:37.011418Z",
     "shell.execute_reply": "2026-11-29T09:54:37.010366Z"
    }
   },
   "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 last part of the lesson uses the package `wikipedia-api` (version 0.16.0, built on `httpx`). The next cell installs it if the session does not have it. The cell after it makes the package read the same saved answers as the page, so the numbers are the same for everyone; to ask the real Wikipedia with any title, set `USE_SAVED_ANSWERS = False` in it, once, for one page: a class that asks together sends many requests from one address."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "c006",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-29T09:54:37.013174Z",
     "iopub.status.busy": "2026-11-29T09:54:37.013006Z",
     "iopub.status.idle": "2026-11-29T09:54:37.090458Z",
     "shell.execute_reply": "2026-11-29T09:54:37.089005Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "wikipedia-api 0.16.0 (if it is not 0.16.0, restart the session and run the notebook again)\n"
     ]
    }
   ],
   "source": [
    "from importlib.metadata import PackageNotFoundError, version\n",
    "try:\n",
    "    installed = version('wikipedia-api')\n",
    "except PackageNotFoundError:\n",
    "    installed = None\n",
    "if installed != '0.16.0':   # the lesson is written for this version (built on httpx); an older one asks the real service\n",
    "    !pip install -q wikipedia-api==0.16.0\n",
    "import wikipediaapi\n",
    "print('wikipedia-api', version('wikipedia-api'), '(if it is not 0.16.0, restart the session and run the notebook again)')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "c007",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-29T09:54:37.093138Z",
     "iopub.status.busy": "2026-11-29T09:54:37.092953Z",
     "iopub.status.idle": "2026-11-29T09:54:37.100568Z",
     "shell.execute_reply": "2026-11-29T09:54:37.099256Z"
    }
   },
   "outputs": [],
   "source": [
    "USE_SAVED_ANSWERS = True   # False: ask the real Wikipedia (one person, one page)\n",
    "\n",
    "# This cell makes wikipedia-api read the saved answers of the course site instead of the real service. You do not need to read it.\n",
    "import json\n",
    "import httpx\n",
    "import requests\n",
    "\n",
    "BASE = 'https://dvirross.com/materials/courses/intro-data-science/wikipedia-api/'\n",
    "\n",
    "\n",
    "class PageNotSaved(Exception):\n",
    "    pass\n",
    "\n",
    "\n",
    "_real_transport = httpx.HTTPTransport\n",
    "\n",
    "\n",
    "def use_real_service():\n",
    "    \"\"\"Back to the real transport of httpx (an object `Wikipedia` made earlier keeps the transport it was made with: make it again).\"\"\"\n",
    "    httpx.HTTPTransport = _real_transport\n",
    "\n",
    "\n",
    "def use_saved_answers(base=BASE):\n",
    "    if getattr(httpx.HTTPTransport, '_saved_answers', False):\n",
    "        return\n",
    "    saved = {}\n",
    "\n",
    "    def read(name):\n",
    "        answer = requests.get(base + name, headers={'User-Agent': 'IntroDataScienceCourse/1.0 (teaching example; contact via dvirross.com)'}, timeout=30)\n",
    "        return answer.status_code, answer.content\n",
    "\n",
    "    class SavedTransport(httpx.BaseTransport):\n",
    "        _saved_answers = True\n",
    "\n",
    "        def __init__(self, *args, **kwargs):\n",
    "            pass\n",
    "\n",
    "        def handle_request(self, request):\n",
    "            params = request.url.params\n",
    "            if request.url.host != 'en.wikipedia.org' or request.url.path != '/w/api.php':\n",
    "                raise PageNotSaved('Only the English Wikipedia is answered from the saved copies.')\n",
    "            if not saved:\n",
    "                status, content = read('manifest.json')\n",
    "                if status != 200:\n",
    "                    raise PageNotSaved('The saved answers could not be loaded (' + str(status) + ').')\n",
    "                saved.update(json.loads(content)['entries'])\n",
    "            cont = ';'.join(sorted(k + '=' + v for k, v in params.items() if k.endswith('continue') and k != 'continue'))\n",
    "            entry = saved.get('|'.join([params.get('prop', ''), params.get('titles', ''), cont]))\n",
    "            if entry is None:\n",
    "                raise PageNotSaved('This page was not saved for this lesson (' + params.get('prop', '') + ' of \"' + params.get('titles', '') + '\"). Set the switch to use the real service.')\n",
    "            status, content = read(entry['file'])\n",
    "            if status != 200:\n",
    "                raise PageNotSaved('The saved answer ' + entry['file'] + ' could not be loaded (' + str(status) + ').')\n",
    "            return httpx.Response(200, content=content, headers={'content-type': 'application/json; charset=utf-8'}, request=request)\n",
    "\n",
    "    httpx.HTTPTransport = SavedTransport\n",
    "\n",
    "if USE_SAVED_ANSWERS:\n",
    "    use_saved_answers()\n",
    "else:\n",
    "    use_real_service()   # run the cell that makes `wiki` again after a change of the switch"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c008",
   "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": 4,
   "id": "c009",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-29T09:54:37.102438Z",
     "iopub.status.busy": "2026-11-29T09:54:37.102209Z",
     "iopub.status.idle": "2026-11-29T09:54:37.111943Z",
     "shell.execute_reply": "2026-11-29T09:54:37.108632Z"
    }
   },
   "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",
    "        'a91b9a9504c1'\n",
    "    ],\n",
    "    '2': [\n",
    "        '3fdba35f04dc'\n",
    "    ],\n",
    "    '3': [\n",
    "        'c78227ee5628',\n",
    "        'b92a24bd26b0',\n",
    "        '71d64810c1e5'\n",
    "    ],\n",
    "    '4': [\n",
    "        '84497ea987e0'\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": "c010",
   "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. The package of the last part of the lesson needs more answers; they were asked the same way, on 22 November 2026, and saved as 29 files about nine pages. 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 and 22 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": 5,
   "id": "c011",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-29T09:54:37.114542Z",
     "iopub.status.busy": "2026-11-29T09:54:37.114356Z",
     "iopub.status.idle": "2026-11-29T09:54:37.120760Z",
     "shell.execute_reply": "2026-11-29T09:54:37.119680Z"
    }
   },
   "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": "c012",
   "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": 6,
   "id": "c013",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-29T09:54:37.122361Z",
     "iopub.status.busy": "2026-11-29T09:54:37.122207Z",
     "iopub.status.idle": "2026-11-29T09:54:37.126833Z",
     "shell.execute_reply": "2026-11-29T09:54:37.125764Z"
    }
   },
   "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": "c014",
   "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. The method `response.raise_for_status()` makes the same check in one line: it does nothing for a good code, and stops the program with an error for a code of 400 or more.\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": 7,
   "id": "c015",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-29T09:54:37.128407Z",
     "iopub.status.busy": "2026-11-29T09:54:37.128251Z",
     "iopub.status.idle": "2026-11-29T09:54:37.133010Z",
     "shell.execute_reply": "2026-11-29T09:54:37.131974Z"
    }
   },
   "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": "c016",
   "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": 8,
   "id": "c017",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-29T09:54:37.136153Z",
     "iopub.status.busy": "2026-11-29T09:54:37.135966Z",
     "iopub.status.idle": "2026-11-29T09:54:37.139719Z",
     "shell.execute_reply": "2026-11-29T09:54:37.138554Z"
    }
   },
   "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": "c018",
   "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": 9,
   "id": "c019",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-29T09:54:37.141719Z",
     "iopub.status.busy": "2026-11-29T09:54:37.141566Z",
     "iopub.status.idle": "2026-11-29T09:54:37.147733Z",
     "shell.execute_reply": "2026-11-29T09:54:37.144345Z"
    }
   },
   "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": "c020",
   "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."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c021",
   "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. Several titles in one question and one item per page in the answer. It helps with: asking a service about several items at once."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c022",
   "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": "c023",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-29T09:54:37.149281Z",
     "iopub.status.busy": "2026-11-29T09:54:37.149122Z",
     "iopub.status.idle": "2026-11-29T09:54:37.154588Z",
     "shell.execute_reply": "2026-11-29T09:54:37.153575Z"
    }
   },
   "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": "c024",
   "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",
    "## The links of a page\n",
    "\n",
    "The property `links` returns the pages that a page links to. The parameters of each property have a prefix of their own, so that parameters of different properties do not mix: `ex` for `extracts`, as in `exintro`, and `pl` for `links`, short for page links. 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": 11,
   "id": "c025",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-29T09:54:37.156259Z",
     "iopub.status.busy": "2026-11-29T09:54:37.156103Z",
     "iopub.status.idle": "2026-11-29T09:54:37.162948Z",
     "shell.execute_reply": "2026-11-29T09:54:37.160400Z"
    }
   },
   "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": "c026",
   "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": 12,
   "id": "c027",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-29T09:54:37.164833Z",
     "iopub.status.busy": "2026-11-29T09:54:37.164589Z",
     "iopub.status.idle": "2026-11-29T09:54:37.168034Z",
     "shell.execute_reply": "2026-11-29T09:54:37.167050Z"
    }
   },
   "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": "c028",
   "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",
    "## 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": 13,
   "id": "c029",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-29T09:54:37.169798Z",
     "iopub.status.busy": "2026-11-29T09:54:37.169633Z",
     "iopub.status.idle": "2026-11-29T09:54:37.174997Z",
     "shell.execute_reply": "2026-11-29T09:54:37.173747Z"
    }
   },
   "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": "c030",
   "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": 14,
   "id": "c031",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-29T09:54:37.177152Z",
     "iopub.status.busy": "2026-11-29T09:54:37.176981Z",
     "iopub.status.idle": "2026-11-29T09:54:37.181439Z",
     "shell.execute_reply": "2026-11-29T09:54:37.179779Z"
    }
   },
   "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": "c032",
   "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": 15,
   "id": "c033",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-29T09:54:37.183925Z",
     "iopub.status.busy": "2026-11-29T09:54:37.183714Z",
     "iopub.status.idle": "2026-11-29T09:54:37.189162Z",
     "shell.execute_reply": "2026-11-29T09:54:37.187541Z"
    }
   },
   "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": "c034",
   "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",
    "## A package that asks for us\n",
    "\n",
    "Writing the endpoint, the parameters and the path into the answer is the same work for every question, so many services have a **[package](https://dvirross.com/courses/intro-data-science/glossary#package)** (a library): ready-made Python code that writes the requests and reads the answers for us. For Wikipedia it is `wikipedia-api`, which Colab installs with `pip install wikipedia-api` and which we import as `wikipediaapi`. We create its object `Wikipedia` with a user agent (it refuses to work without one) and a language, and ask it for a page by its title with `page`, which returns an **[object](https://dvirross.com/courses/intro-data-science/glossary#object)** that holds the page. Its method `exists()` says whether the page exists, and its attributes `title`, `summary` and `links` hold the title, the summary and the links (see [method and attribute](https://dvirross.com/courses/intro-data-science/glossary#method))."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c035",
   "metadata": {},
   "source": [
    "In the notebooks the cell of the setup makes the package read the same saved answers as the page. To ask the real Wikipedia, with any title, set `USE_SAVED_ANSWERS = False` in that cell, once, for one page: a class that asks together sends many requests from one address."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "c036",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-29T09:54:37.190779Z",
     "iopub.status.busy": "2026-11-29T09:54:37.190628Z",
     "iopub.status.idle": "2026-11-29T09:54:37.208358Z",
     "shell.execute_reply": "2026-11-29T09:54:37.207131Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "Field-programmable gate array\n",
      "A field-programmable gate array (FPGA) is a type of configurable integrated circuit that can be repeatedly programmed after manufacturing\n",
      "1951 766\n"
     ]
    }
   ],
   "source": [
    "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.exists())\n",
    "print(page.title)\n",
    "print(page.summary.split('. ')[0])\n",
    "print(len(page.summary), len(page.links))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c037",
   "metadata": {},
   "source": [
    "The summary has the same 1,951 characters as the extract that we read with `requests`, and the first sentence is the same. The package reports 766 links where the first answer of the service held 500: when an answer says that it continues, the package repeats the request with the `continue` that the answer gives, as in the loop of [all the links of a page](#all-the-links-of-a-page) in the self-study part below, and returns all the links of the page."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c038",
   "metadata": {},
   "source": [
    "**The same question as a direct call to the API**"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c039",
   "metadata": {},
   "source": [
    "Without the package we write the question ourselves, as in the parts above: an endpoint, parameters, and the path in the answer down to the summary.\n",
    "\n",
    "```python\n",
    "summary_answer = requests.get(\n",
    "    'https://en.wikipedia.org/w/api.php',\n",
    "    params={\n",
    "        'action': 'query', 'format': 'json', 'formatversion': 2,\n",
    "        'prop': 'extracts', 'exintro': 1, 'explaintext': 1,\n",
    "        'titles': 'Field-programmable gate array',\n",
    "    },\n",
    "    headers=headers,\n",
    "    timeout=30,\n",
    ").json()\n",
    "text = summary_answer['query']['pages'][0]['extract']\n",
    "```\n",
    "\n",
    "The links come from a second question, `prop=links`, with the loop over `continue` that is shown in the self-study part below. This code is what `page.summary` and `page.links` save us."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c040",
   "metadata": {},
   "source": [
    "## What the package does underneath\n",
    "\n",
    "The package does not ask anything new: every answer that it gives comes from a question of the kind that we wrote by hand. Asking for a page with `wiki.page(...)` sends nothing yet; the question goes out when we read something that needs the service.\n",
    "\n",
    "| In our code | The question that the package sends |\n",
    "| --- | --- |\n",
    "| `page.exists()` | `prop=info`: facts about the page |\n",
    "| `page.summary` | `prop=extracts` with `explaintext`: the text of the page; the summary is the part before the first heading |\n",
    "| `page.links` | `prop=links`, repeated with the `continue` of each answer until an answer has none |\n",
    "\n",
    "It sends the user agent that we gave it, and when the service answers with the status code 429 it waits and tries again. The price of the short code is that we do not see the parameters or the structure of the answer. When something goes wrong, or when a service has no package, we go back to `requests`, `params` and `json()`.\n",
    "\n",
    "A page that does not exist gets `False` from `exists()` and an empty text as its summary, like the empty default `''` that we chose with `get`. A program checks `exists()` before it reads the links of a page:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "c041",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-29T09:54:37.210170Z",
     "iopub.status.busy": "2026-11-29T09:54:37.210010Z",
     "iopub.status.idle": "2026-11-29T09:54:37.225356Z",
     "shell.execute_reply": "2026-11-29T09:54:37.224048Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "RISC-V 346\n",
      "Verilog 439\n",
      "RISC-VI no such page\n"
     ]
    }
   ],
   "source": [
    "for title in ['RISC-V', 'Verilog', 'RISC-VI']:\n",
    "    page = wiki.page(title)\n",
    "    if page.exists():\n",
    "        print(title, len(page.links))\n",
    "    else:\n",
    "        print(title, 'no such page')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c042",
   "metadata": {},
   "source": [
    "**The same check as a direct call to the API**"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c043",
   "metadata": {},
   "source": [
    "Without the package we ask about several titles at once, and a page that does not exist arrives as an item with the key `missing` and no `extract`, as in the part [A key that is missing](#a-key-that-is-missing):\n",
    "\n",
    "```python\n",
    "pages = answer['query']['pages']\n",
    "for page in pages:\n",
    "    if page.get('missing'):\n",
    "        print(page['title'], 'no such page')\n",
    "    else:\n",
    "        print(page['title'], len(page['extract']))\n",
    "```\n",
    "\n",
    "`exists()` of the package is this check, `get('missing')`, without our writing it."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c044",
   "metadata": {},
   "source": [
    "### Practice\n",
    "\n",
    "**Your turn.** The package is ready in the variable `wiki`. Print the length of the summary of the page `'Hardware description language'` in characters and, after a space, the number of its words: the number that `split()` finds."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "c045",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-29T09:54:37.226933Z",
     "iopub.status.busy": "2026-11-29T09:54:37.226761Z",
     "iopub.status.idle": "2026-11-29T09:54:37.229727Z",
     "shell.execute_reply": "2026-11-29T09:54:37.228747Z"
    }
   },
   "outputs": [],
   "source": [
    "# Your turn"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c046",
   "metadata": {},
   "source": [
    "**Expected output (the numbers are hidden)**\n",
    "\n",
    "```text\n",
    "<number> <number>\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "c047",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-29T09:54:37.231383Z",
     "iopub.status.busy": "2026-11-29T09:54:37.231237Z",
     "iopub.status.idle": "2026-11-29T09:54:37.234446Z",
     "shell.execute_reply": "2026-11-29T09:54:37.233531Z"
    }
   },
   "outputs": [],
   "source": [
    "check(1)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c048",
   "metadata": {},
   "source": [
    "> **Hint**\n",
    ">\n",
    "> Ask for the page with `wiki.page(title)` and read its `summary`. The function `len` of a text counts characters, and the method `split()` with no argument cuts a text at spaces and line breaks and returns a list of its words, which `len` counts."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c049",
   "metadata": {},
   "source": [
    "The method `lower()` returns a text in lowercase letters, and `in` also tests whether a text contains another one: `'language' in 'Property Specification Language'` is `False`, because the capital letter is a different character, and `'language' in 'Property Specification Language'.lower()` is `True`. The attribute `links` of a page is a dictionary whose keys are the titles of the pages that the page links to, and a loop over a dictionary goes over its keys.\n",
    "\n",
    "**Your turn.** How many of the links of the page `'Verilog'` have a title that contains the word `language`, with a capital letter or without? Print how many there are, as one number."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "c050",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-29T09:54:37.236118Z",
     "iopub.status.busy": "2026-11-29T09:54:37.235977Z",
     "iopub.status.idle": "2026-11-29T09:54:37.238670Z",
     "shell.execute_reply": "2026-11-29T09:54:37.237733Z"
    }
   },
   "outputs": [],
   "source": [
    "# Your turn"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c051",
   "metadata": {},
   "source": [
    "**Expected output (the numbers are hidden)**\n",
    "\n",
    "```text\n",
    "<number>\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "c052",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-29T09:54:37.240451Z",
     "iopub.status.busy": "2026-11-29T09:54:37.240295Z",
     "iopub.status.idle": "2026-11-29T09:54:37.243727Z",
     "shell.execute_reply": "2026-11-29T09:54:37.242791Z"
    }
   },
   "outputs": [],
   "source": [
    "check(2)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c053",
   "metadata": {},
   "source": [
    "> **Hint**\n",
    ">\n",
    "> Ask for the page with `page = wiki.page('Verilog')` and build a list with a list comprehension, `[title for title in page.links if ...]`, whose condition tests the title in lowercase letters: `'language' in title.lower()`. Print the length of the list."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c054",
   "metadata": {},
   "source": [
    "**Your turn.** For each of the titles `'Verilog'`, `'VHDL'` and `'RISC-VI'`, print the title and, after a space, the number of words of its summary. For a page that does not exist, print `no such page` instead of the number."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "c055",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-29T09:54:37.246251Z",
     "iopub.status.busy": "2026-11-29T09:54:37.246093Z",
     "iopub.status.idle": "2026-11-29T09:54:37.249230Z",
     "shell.execute_reply": "2026-11-29T09:54:37.248044Z"
    }
   },
   "outputs": [],
   "source": [
    "# Your turn"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c056",
   "metadata": {},
   "source": [
    "**Expected output (the numbers are hidden)**\n",
    "\n",
    "```text\n",
    "Verilog <number>\n",
    "VHDL <number>\n",
    "RISC-VI no such page\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "c057",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-29T09:54:37.250749Z",
     "iopub.status.busy": "2026-11-29T09:54:37.250603Z",
     "iopub.status.idle": "2026-11-29T09:54:37.253662Z",
     "shell.execute_reply": "2026-11-29T09:54:37.252689Z"
    }
   },
   "outputs": [],
   "source": [
    "check(3)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c058",
   "metadata": {},
   "source": [
    "> **Hint**\n",
    ">\n",
    "> Ask for the page with `wiki.page(title)` and test it with `exists()`: if it exists, cut its `summary` into words and count them, `len(page.summary.split())`, and if not, print the message."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c059",
   "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. Comparing several pages by their number of links, with max and min by a key. It helps with: finding the largest and the smallest by a key."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c060",
   "metadata": {},
   "source": [
    "## The page with the most links\n",
    "\n",
    "The function `max` returns the largest item, and its argument `key` says what to compare. Applied to a dictionary it goes over the keys, and `key` is a small function, a `lambda`, that takes a key and returns what to compare by: for a dictionary `counts` from a title to its number of links, `lambda title: counts[title]` returns the number of links of a title. The function `min` works the same way.\n",
    "\n",
    "**Your turn.** For each of the five titles `'RISC-V'`, `'Hardware description language'`, `'Verilog'`, `'VHDL'` and `'Microcontroller'`, count the links of its page. Print the title of the page with the most links and, after a space, how many times larger it is than the page with the fewest links, rounded to one digit after the decimal point."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "c061",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-29T09:54:37.255082Z",
     "iopub.status.busy": "2026-11-29T09:54:37.254924Z",
     "iopub.status.idle": "2026-11-29T09:54:37.257629Z",
     "shell.execute_reply": "2026-11-29T09:54:37.256753Z"
    }
   },
   "outputs": [],
   "source": [
    "# Your turn"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c062",
   "metadata": {},
   "source": [
    "**Expected output (the numbers are hidden)**\n",
    "\n",
    "```text\n",
    "Microcontroller <number>\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "c063",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-29T09:54:37.259024Z",
     "iopub.status.busy": "2026-11-29T09:54:37.258892Z",
     "iopub.status.idle": "2026-11-29T09:54:37.262371Z",
     "shell.execute_reply": "2026-11-29T09:54:37.261083Z"
    }
   },
   "outputs": [],
   "source": [
    "check(4)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c064",
   "metadata": {},
   "source": [
    "> **Hint**\n",
    ">\n",
    "> Build a dictionary `counts` from a title to its number of links, `len(wiki.page(title).links)`, then find the title with the most links with `max` and the title with the fewest with `min`, both with `key`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c065",
   "metadata": {},
   "source": [
    "> **Self-study, importance 3.** This part is for self-study: it is not taught in the lecture, and you read it on your own. A search question and repeating a request to get all the links of a page. It helps with: reading search results and collecting the parts of an answer that comes in parts."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c066",
   "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": 26,
   "id": "c067",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-29T09:54:37.263823Z",
     "iopub.status.busy": "2026-11-29T09:54:37.263672Z",
     "iopub.status.idle": "2026-11-29T09:54:37.268926Z",
     "shell.execute_reply": "2026-11-29T09:54:37.267743Z"
    }
   },
   "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": "c068",
   "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",
    "## 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.\n",
    "- A package such as `wikipedia-api` writes the requests and follows `continue` for us. Underneath it sends the same kind of questions, so the parameters, the status code and the structure of an answer are still what we check when something goes wrong."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c069",
   "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": 27,
   "id": "c070",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-29T09:54:37.270529Z",
     "iopub.status.busy": "2026-11-29T09:54:37.270375Z",
     "iopub.status.idle": "2026-11-29T09:54:37.275448Z",
     "shell.execute_reply": "2026-11-29T09:54:37.274320Z"
    }
   },
   "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
}
