{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "11123e27",
   "metadata": {},
   "source": [
    "# API Reliability and Production Patterns"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "a2216cae",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-08-31T05:51:31.839988Z",
     "iopub.status.busy": "2026-08-31T05:51:31.839729Z",
     "iopub.status.idle": "2026-08-31T05:51:31.884550Z",
     "shell.execute_reply": "2026-08-31T05:51:31.884210Z"
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "import os\n",
    "import time\n",
    "\n",
    "import requests"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8eba0589",
   "metadata": {},
   "source": [
    "API code becomes production code when other code depends on it. Reliability means the client sends data in the format the server expects, keeps secrets out of code, reads nested responses defensively, follows pagination, retries transient failures, and validates responses, instead of assuming every request succeeds and every response has the expected shape."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "df9af619",
   "metadata": {},
   "source": [
    "```{contents}\n",
    ":local:\n",
    ":depth: 2\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "57ea277b",
   "metadata": {},
   "source": [
    "## POST Requests\n",
    "\n",
    "A `GET` request retrieves data. A `POST` request sends data, often to create a record or submit a form. In `requests`, use `json=` when the request body should be JSON. The library serializes the dictionary and sets the appropriate content type."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-57ea277b",
   "metadata": {},
   "source": [
    "```{index} POST request, request body, requests.post()\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "97098b00",
   "metadata": {},
   "source": [
    "### Worked Example: Prepare a JSON POST\n",
    "\n",
    "This example prepares a `POST` request without sending it, so you can inspect what `json=` does: it sets the `Content-Type` header to `application/json` and serializes the dictionary into the request body.\n",
    "\n",
    "`requests.Request()` describes the request you intend to make: the method, URL, and any params, headers, or body. Its `.prepare()` method encodes that description into a `PreparedRequest`, the exact request that would be sent."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-97098b00",
   "metadata": {},
   "source": [
    "```{index} Content-Type header, JSON serialization\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "5af7657c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-08-31T05:51:31.886597Z",
     "iopub.status.busy": "2026-08-31T05:51:31.886481Z",
     "iopub.status.idle": "2026-08-31T05:51:31.888581Z",
     "shell.execute_reply": "2026-08-31T05:51:31.888373Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'name': 'Alice', 'role': 'student'}\n",
      "POST\n",
      "https://api.example.test/users\n",
      "application/json\n",
      "{\"name\": \"Alice\", \"role\": \"student\"}\n"
     ]
    }
   ],
   "source": [
    "import requests\n",
    "\n",
    "payload = {\"name\": \"Alice\", \"role\": \"student\"}\n",
    "\n",
    "req = requests.Request(  # a Request: describes what to send\n",
    "    \"POST\",\n",
    "    \"https://api.example.test/users\",\n",
    "    json=payload,\n",
    ")\n",
    "print(req.json)  # still a Python dict\n",
    "\n",
    "prepared = req.prepare()  # a PreparedRequest: encoded and ready to send\n",
    "\n",
    "print(prepared.method)\n",
    "print(prepared.url)\n",
    "print(prepared.headers[\"Content-Type\"])\n",
    "print(prepared.body.decode())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "post-json-vs-data",
   "metadata": {},
   "source": [
    "The body of a prepared request is stored as bytes, so `.decode()` turns it back into text for printing.\n",
    "\n",
    "Use `json=`, not `data=`, for a JSON API. Passing a dictionary to `data=` sends it form-encoded (`name=Alice&role=student`) with the content type `application/x-www-form-urlencoded`.\n",
    "\n",
    "`.prepare()` is for inspecting a request. To send one, call `requests.post()` with the same arguments plus a timeout. The host `api.example.test` is a placeholder, so this snippet is shown rather than run:\n",
    "\n",
    "```python\n",
    "response = requests.post(\n",
    "    \"https://api.example.test/users\",\n",
    "    json=payload,\n",
    "    timeout=10,\n",
    ")\n",
    "response.raise_for_status()  # a successful create usually returns 201 Created\n",
    "created = response.json()    # the server's copy of the new record\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "372a5a5f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-08-31T05:51:31.889803Z",
     "iopub.status.busy": "2026-08-31T05:51:31.889694Z",
     "iopub.status.idle": "2026-08-31T05:51:31.891438Z",
     "shell.execute_reply": "2026-08-31T05:51:31.891186Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "POST\n",
      "{}\n"
     ]
    }
   ],
   "source": [
    "### Exercise: POST Payload\n",
    "#   Prepare a POST request to https://api.example.test/events whose JSON body\n",
    "#   sets \"event_type\" to \"login\" and \"count\" to 3. Print the method and the\n",
    "#   decoded body.\n",
    "#   Print exactly:\n",
    "#   POST\n",
    "#   {\"event_type\": \"login\", \"count\": 3}\n",
    "### Your code starts here\n",
    "payload = {}\n",
    "prepared = requests.Request(\"POST\", \"https://api.example.test/events\", json=payload).prepare()\n",
    "print(prepared.method)\n",
    "print(prepared.body.decode())\n",
    "### Your code ends here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "114a290d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-08-31T05:51:31.892641Z",
     "iopub.status.busy": "2026-08-31T05:51:31.892570Z",
     "iopub.status.idle": "2026-08-31T05:51:31.894323Z",
     "shell.execute_reply": "2026-08-31T05:51:31.894122Z"
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "POST\n",
      "{\"event_type\": \"login\", \"count\": 3}\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "payload = {\"event_type\": \"login\", \"count\": 3}\n",
    "prepared = requests.Request(\"POST\", \"https://api.example.test/events\", json=payload).prepare()\n",
    "print(prepared.method)\n",
    "print(prepared.body.decode())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "af07017c",
   "metadata": {},
   "source": [
    "## Headers and API Keys\n",
    "\n",
    "Headers carry request metadata. Authentication tokens often belong in an `Authorization` header, not in the URL, usually in the form `Bearer <token>`. *Bearer* means that whoever holds (bears) the token is treated as authorized, which is why the token must stay secret. Some APIs expect the key in a custom header instead, most commonly `X-API-Key`; the API's documentation tells you which header name to use. Keep real secrets out of notebooks and source files: read them from environment variables and fail clearly when they are missing."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-af07017c",
   "metadata": {},
   "source": [
    "```{index} HTTP header, API key, environment variable\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a157bdd1",
   "metadata": {},
   "source": [
    "### Worked Example: Build Auth Headers\n",
    "\n",
    "This function reads the API key from an environment variable and places it in an `Authorization` header. If the variable is not set, it falls back to a placeholder so the example still runs.\n",
    "\n",
    "```bash\n",
    "(.venv) user✪host:~/workspace/py$ env\n",
    "SHELL=/opt/homebrew/bin/bash\n",
    "COLORTERM=truecolor\n",
    "...\n",
    "...\n",
    "GEMINI_API_KEY=############################\n",
    "...\n",
    "OPENAI_API_KEY=sk-proj-############################-\n",
    "...\n",
    "..."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-a157bdd1",
   "metadata": {},
   "source": [
    "```{index} Authorization header, bearer token, os.environ.get()\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "fd2600f2",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-08-31T05:51:31.895384Z",
     "iopub.status.busy": "2026-08-31T05:51:31.895322Z",
     "iopub.status.idle": "2026-08-31T05:51:31.897220Z",
     "shell.execute_reply": "2026-08-31T05:51:31.897042Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Bearer demo-token\n",
      "application/json\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "\n",
    "def build_headers(token_env_var=\"DEMO_API_KEY\"):\n",
    "    token = os.environ.get(token_env_var)\n",
    "    if token is None:\t\t\t\t\t\n",
    "        token = \"demo-token\"\t\t\t### fallback\n",
    "    return {\n",
    "        \"Authorization\": f\"Bearer {token}\",\n",
    "        \"Accept\": \"application/json\",\n",
    "    }\n",
    "\n",
    "headers = build_headers()\n",
    "print(headers[\"Authorization\"])\n",
    "print(headers[\"Accept\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "headers-fail-fast",
   "metadata": {},
   "source": [
    "The fallback keeps this example runnable. In real code, replace it with an error so a missing key is caught immediately:\n",
    "\n",
    "```python\n",
    "token = os.environ.get(\"DEMO_API_KEY\")\n",
    "if not token:\n",
    "    raise RuntimeError(\"Set the DEMO_API_KEY environment variable first\")\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "ck-hdr-q",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "None\n",
      "None\n"
     ]
    }
   ],
   "source": [
    "### Exercise: API Key Header\n",
    "#   Some APIs expect the key in a custom header instead of `Authorization`.\n",
    "#   Complete `build_key_headers()` so it reads the key from the environment\n",
    "#   variable named by `env_var`, uses `fallback` when the variable is not set,\n",
    "#   and returns a dictionary with an `X-API-Key` header and an `Accept` header\n",
    "#   of `application/json`. The test code attaches the headers to a prepared\n",
    "#   GET request.\n",
    "#   Print exactly:\n",
    "#   test-key\n",
    "#   application/json\n",
    "def build_key_headers(env_var=\"REPORTS_API_KEY\", fallback=\"test-key\"):\n",
    "    ### Your code starts here\n",
    "    return {}\n",
    "    ### Your code ends here\n",
    "\n",
    "headers = build_key_headers()\n",
    "prepared = requests.Request(\"GET\", \"https://api.example.test/reports\", headers=headers).prepare()\n",
    "print(prepared.headers.get(\"X-API-Key\"))\n",
    "print(prepared.headers.get(\"Accept\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "ck-hdr-sol",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "test-key\n",
      "application/json\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "def build_key_headers(env_var=\"REPORTS_API_KEY\", fallback=\"test-key\"):\n",
    "    api_key = os.environ.get(env_var, fallback)\n",
    "    return {\n",
    "        \"X-API-Key\": api_key,\n",
    "        \"Accept\": \"application/json\",\n",
    "    }\n",
    "\n",
    "headers = build_key_headers()\n",
    "prepared = requests.Request(\"GET\", \"https://api.example.test/reports\", headers=headers).prepare()\n",
    "print(prepared.headers.get(\"X-API-Key\"))\n",
    "print(prepared.headers.get(\"Accept\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cb92d1f3",
   "metadata": {},
   "source": [
    "## Nested JSON Parsing\n",
    "\n",
    "Many API responses contain dictionaries inside lists inside dictionaries. Direct indexing is concise when the response contract is guaranteed. The `.get()` method is safer when fields may be optional."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-cb92d1f3",
   "metadata": {},
   "source": [
    "```{index} nested JSON, defensive parsing\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e778ee2f",
   "metadata": {},
   "source": [
    "### Worked Example: Direct and Defensive Access\n",
    "\n",
    "The same payload is read in two ways. Direct indexing reaches the user's name, which the response contract guarantees. The metrics list is optional, so it is read defensively: `.get()` supplies an empty list when the `metrics` key is missing, and the conditional returns `0` when the list is empty. Neither case raises a `KeyError` or an `IndexError`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-e778ee2f",
   "metadata": {},
   "source": [
    "```{index} dict.get()\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "8a7ad2f6",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-08-31T05:51:31.898354Z",
     "iopub.status.busy": "2026-08-31T05:51:31.898287Z",
     "iopub.status.idle": "2026-08-31T05:51:31.899943Z",
     "shell.execute_reply": "2026-08-31T05:51:31.899755Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Nia\n",
      "42\n"
     ]
    }
   ],
   "source": [
    "payload = {\n",
    "    \"user\": {\n",
    "        \"id\": 101,\n",
    "        \"profile\": {\"name\": \"Nia\", \"department\": \"Analytics\"},\n",
    "    },\n",
    "    \"metrics\": [{\"name\": \"requests\", \"value\": 42}],\n",
    "}\n",
    "\n",
    "name = payload[\"user\"][\"profile\"][\"name\"]\n",
    "metrics = payload.get(\"metrics\", [])\n",
    "first_metric = metrics[0].get(\"value\", 0) if metrics else 0\n",
    "\n",
    "print(name)\n",
    "print(first_metric)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "nested-null",
   "metadata": {},
   "source": [
    "`.get()` protects against a missing key, not against a key whose value is `null`. With `{\"user\": None}`, `payload.get(\"user\", {})` returns `None`, and the next `.get()` raises `AttributeError`. When an API can return `null` for a nested object, write `(payload.get(\"user\") or {})`.\n",
    "\n",
    "```python\n",
    "user = payload.get(\"user\") or {}\n",
    "profile = user.get(\"profile\") or {}\n",
    "name = profile.get(\"name\") or \"Unknown\"\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "fbedd891",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-08-31T05:51:31.900979Z",
     "iopub.status.busy": "2026-08-31T05:51:31.900916Z",
     "iopub.status.idle": "2026-08-31T05:51:31.902528Z",
     "shell.execute_reply": "2026-08-31T05:51:31.902288Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "None\n",
      "None\n",
      "None\n"
     ]
    }
   ],
   "source": [
    "### Exercise: Defensive Parsing\n",
    "#   Write `get_department(payload)` so it returns the nested department value\n",
    "#   when present and 'unknown' otherwise, including when \"user\" is None.\n",
    "#   Print exactly:\n",
    "#   Analytics\n",
    "#   unknown\n",
    "#   unknown\n",
    "def get_department(payload):\n",
    "    ### Your code starts here\n",
    "    return None\n",
    "    ### Your code ends here\n",
    "\n",
    "print(get_department(payload))\n",
    "print(get_department({\"user\": {}}))\n",
    "print(get_department({\"user\": None}))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "6c769e90",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-08-31T05:51:31.903538Z",
     "iopub.status.busy": "2026-08-31T05:51:31.903463Z",
     "iopub.status.idle": "2026-08-31T05:51:31.905029Z",
     "shell.execute_reply": "2026-08-31T05:51:31.904860Z"
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Analytics\n",
      "unknown\n",
      "unknown\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "def get_department(payload):\n",
    "    user = payload.get(\"user\") or {}\n",
    "    profile = user.get(\"profile\") or {}\n",
    "    return profile.get(\"department\", \"unknown\")\n",
    "\n",
    "print(get_department(payload))\n",
    "print(get_department({\"user\": {}}))\n",
    "print(get_department({\"user\": None}))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f7f7d56b",
   "metadata": {},
   "source": [
    "## Pagination Patterns\n",
    "\n",
    "APIs often return large result sets in pages. A client should keep requesting pages until the response says there is no next page. Page-based APIs often use an integer page number; cursor-based APIs use a token returned by the previous response. With a cursor, each response includes a value such as `next_cursor` that you send with the next request, and a missing or `None` cursor means you have reached the last page."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-f7f7d56b",
   "metadata": {},
   "source": [
    "```{index} pagination, cursor-based pagination\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1ea9fc25",
   "metadata": {},
   "source": [
    "### Worked Example: Page-Based Pagination\n",
    "\n",
    "A small dictionary stands in for an API that returns one page at a time. `fetch_all_pages()` keeps requesting the next page and collecting its items until a page reports `next_page` as `None`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-1ea9fc25",
   "metadata": {},
   "source": [
    "```{index} page-based pagination\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "43457dce",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-08-31T05:51:31.906069Z",
     "iopub.status.busy": "2026-08-31T05:51:31.906012Z",
     "iopub.status.idle": "2026-08-31T05:51:31.907912Z",
     "shell.execute_reply": "2026-08-31T05:51:31.907740Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['a', 'b', 'c', 'd', 'e']\n"
     ]
    }
   ],
   "source": [
    "pages = {\n",
    "    1: {\"items\": [\"a\", \"b\"], \"next_page\": 2},\n",
    "    2: {\"items\": [\"c\", \"d\"], \"next_page\": 3},\n",
    "    3: {\"items\": [\"e\"], \"next_page\": None},\n",
    "}\n",
    "\n",
    "def get_page(page_number):\n",
    "    return pages[page_number]\n",
    "\n",
    "def fetch_all_pages(get_page_fn, first_page=1):\n",
    "    items = []\n",
    "    page = first_page\n",
    "    while page is not None:\n",
    "        payload = get_page_fn(page)\n",
    "        items.extend(payload[\"items\"])\n",
    "        page = payload[\"next_page\"]\n",
    "    return items\n",
    "\n",
    "print(fetch_all_pages(get_page))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "ck-cursor-q",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[]\n"
     ]
    }
   ],
   "source": [
    "### Exercise: Cursor-Based Pagination\n",
    "#   `cursor_pages` stands in for a cursor-based API. Each response holds a\n",
    "#   `results` list and a `next_cursor` token that names the next page; the\n",
    "#   last page sets `next_cursor` to None. Complete `fetch_all_cursor(get_fn)`\n",
    "#   so it starts at the cursor \"start\", follows each `next_cursor` token, and\n",
    "#   returns every result in order.\n",
    "#   Print exactly:\n",
    "#   [101, 102, 103, 104, 105]\n",
    "cursor_pages = {\n",
    "    \"start\": {\"results\": [101, 102], \"next_cursor\": \"k7\"},\n",
    "    \"k7\": {\"results\": [103, 104], \"next_cursor\": \"m2\"},\n",
    "    \"m2\": {\"results\": [105], \"next_cursor\": None},\n",
    "}\n",
    "\n",
    "def get_by_cursor(cursor):\n",
    "    return cursor_pages[cursor]\n",
    "\n",
    "def fetch_all_cursor(get_fn, first_cursor=\"start\"):\n",
    "    results = []\n",
    "    ### Your code starts here\n",
    "\n",
    "    ### Your code ends here\n",
    "    return results\n",
    "\n",
    "print(fetch_all_cursor(get_by_cursor))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "ck-cursor-sol",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[101, 102, 103, 104, 105]\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "def fetch_all_cursor(get_fn, first_cursor=\"start\"):\n",
    "    results = []\n",
    "    cursor = first_cursor\n",
    "    while cursor is not None:\n",
    "        payload = get_fn(cursor)\n",
    "        results.extend(payload[\"results\"])\n",
    "        cursor = payload[\"next_cursor\"]\n",
    "    return results\n",
    "\n",
    "print(fetch_all_cursor(get_by_cursor))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9d00e74e",
   "metadata": {},
   "source": [
    "## Retry with Exponential Backoff\n",
    "\n",
    "Retries help with transient failures: timeouts, rate limits, and temporary server errors. A rate-limited request returns 429 Too Many Requests, often with a `Retry-After` header that says how long to wait (usually a number of seconds). When the header is present, wait that long instead of using your own backoff delay. **Exponential backoff** increases the delay after each failed attempt. In production, add jitter so many clients do not retry at exactly the same time. The examples below leave jitter out so their output is the same on every run. Adding it takes one change, plus `import random`: `delay = base_delay * 2 ** (attempt - 1) * random.uniform(0.5, 1.5)`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-9d00e74e",
   "metadata": {},
   "source": [
    "```{index} exponential backoff, retry, jitter\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7207e5cb",
   "metadata": {},
   "source": [
    "### Worked Example: Retry a Flaky Function\n",
    "\n",
    "`FlakySource` raises a timeout a set number of times before it succeeds, which mimics a temporary network problem. `retry_call()` tries again after each failure, doubling the wait each time, and re-raises the error if the last attempt also fails."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-7207e5cb",
   "metadata": {},
   "source": [
    "```{index} requests.Timeout\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "d8d944a6",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-08-31T05:51:31.908904Z",
     "iopub.status.busy": "2026-08-31T05:51:31.908850Z",
     "iopub.status.idle": "2026-08-31T05:51:31.945899Z",
     "shell.execute_reply": "2026-08-31T05:51:31.945638Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'status': 'ok', 'calls': 3}\n"
     ]
    }
   ],
   "source": [
    "import time\n",
    "\n",
    "import requests\n",
    "\n",
    "class FlakySource:\n",
    "    def __init__(self, failures_before_success):\n",
    "        self.failures_before_success = failures_before_success\n",
    "        self.calls = 0\n",
    "\n",
    "    def get(self):\n",
    "        self.calls += 1\n",
    "        if self.calls <= self.failures_before_success:\n",
    "            raise requests.Timeout(\"temporary timeout\")\n",
    "        return {\"status\": \"ok\", \"calls\": self.calls}\n",
    "\n",
    "def retry_call(call_fn, retries=3, base_delay=0.01):\n",
    "    for attempt in range(1, retries + 1):\n",
    "        try:\n",
    "            return call_fn()\n",
    "        except requests.Timeout:\n",
    "            if attempt == retries:\n",
    "                raise\n",
    "            delay = base_delay * (2 ** (attempt - 1))\n",
    "            time.sleep(delay)\n",
    "\n",
    "source = FlakySource(failures_before_success=2)\n",
    "print(retry_call(source.get, retries=4))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "retry-call-caller",
   "metadata": {},
   "source": [
    "`retry_call()` retries whatever function it is given; it cannot tell a GET from a POST. Deciding whether a call is safe to repeat is the caller's job, and the next subsection gives the rule."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a7a39340",
   "metadata": {},
   "source": [
    "### Which Requests Are Safe to Retry\n",
    "\n",
    "A timeout does not tell you whether the server received the request. If it did, a retry sends the same request a second time. That is harmless for an idempotent method such as `GET`, `PUT`, or `DELETE`, because repeating it leaves the server in the same state (see the methods table in [12.1 API Basics](1201-apis.ipynb)). Repeating a `POST` can create a second order or charge a card twice. A careful client therefore retries automatically only when two conditions hold: the method is idempotent, and the failure is transient, such as a timeout or a `5xx` status.\n",
    "\n",
    "Two details from the method table in the previous section matter once your code retries requests:\n",
    "\n",
    "- **PATCH is idempotent only sometimes.** The HTTP standard does not require it, so it depends on the body. Setting a field to a fixed value, such as `{\"units\": \"celsius\"}`, leaves the record the same however many times you send it. A PATCH that increments a counter or appends to a list changes the record again each time.\n",
    "- **PUT replaces the whole record.** It is safe to repeat, but any field you leave out may be erased, while PATCH sends only the fields that change.\n",
    "\n",
    "APIs that must accept retried `POST` requests often let the client send an `Idempotency-Key` header with a unique value. The server remembers the key and ignores a second request that carries it."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "71d5c754",
   "metadata": {},
   "source": [
    "```{index} idempotent, Idempotency-Key header\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "cdfc1045",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "GET 503: retry=True\n",
      "PUT 500: retry=True\n",
      "POST 503: retry=False\n",
      "GET 404: retry=False\n"
     ]
    }
   ],
   "source": [
    "IDEMPOTENT_METHODS = {\"GET\", \"PUT\", \"DELETE\"}\n",
    "\n",
    "def should_retry(method, status_code):\n",
    "    \"\"\"Retry only idempotent requests that failed with a server error.\"\"\"\n",
    "    return method.upper() in IDEMPOTENT_METHODS and status_code >= 500\n",
    "\n",
    "for method, status in [(\"GET\", 503), (\"PUT\", 500), (\"POST\", 503), (\"GET\", 404)]:\n",
    "    print(f\"{method} {status}: retry={should_retry(method, status)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "should-retry-scope",
   "metadata": {},
   "source": [
    "`should_retry()` covers the status-code half of the rule. The timeout half is handled the way `retry_call()` does it, by catching `requests.Timeout`, and the same method check applies there. A 429 response is a separate case: wait for `Retry-After`, then try again. Treating every `5xx` status as temporary is also a simplification: 501 Not Implemented, for example, fails the same way every time."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "ck-retry-q",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "({'status': 503}, [])\n",
      "({'status': 404}, [])\n",
      "({'status': 503}, [])\n"
     ]
    }
   ],
   "source": [
    "### Exercise: Retry on Server Errors\n",
    "#   A 5xx status code usually means the server had a temporary problem, so a\n",
    "#   GET request like this one is worth retrying. `make_fake_call()` returns a\n",
    "#   stand-in function that replies with the given status codes in order. Complete\n",
    "#   `retry_on_server_error(call_fn)` so it calls `call_fn()`, retries with\n",
    "#   exponential backoff while the status is 500 or higher, and returns a tuple\n",
    "#   of the final response and the list of delays it waited. After `retries`\n",
    "#   attempts, return the last response even if it is still an error.\n",
    "#   Print exactly:\n",
    "#   ({'status': 200}, [0.001, 0.002])\n",
    "#   ({'status': 404}, [])\n",
    "#   ({'status': 503}, [0.001, 0.002, 0.004])\n",
    "def make_fake_call(statuses):\n",
    "    replies = iter(statuses)\n",
    "\n",
    "    def call():\n",
    "        return {\"status\": next(replies)}\n",
    "\n",
    "    return call\n",
    "\n",
    "def retry_on_server_error(call_fn, retries=4, base_delay=0.001):\n",
    "    delays = []\n",
    "    ### Your code starts here\n",
    "    response = call_fn()\n",
    "    ### Your code ends here\n",
    "    return response, delays\n",
    "\n",
    "print(retry_on_server_error(make_fake_call([503, 500, 200])))\n",
    "print(retry_on_server_error(make_fake_call([404])))\n",
    "print(retry_on_server_error(make_fake_call([503, 503, 503, 503])))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "ck-retry-sol",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "({'status': 200}, [0.001, 0.002])\n",
      "({'status': 404}, [])\n",
      "({'status': 503}, [0.001, 0.002, 0.004])\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "def retry_on_server_error(call_fn, retries=4, base_delay=0.001):\n",
    "    delays = []\n",
    "    for attempt in range(1, retries + 1):\n",
    "        response = call_fn()\n",
    "        if response[\"status\"] < 500 or attempt == retries:\n",
    "            return response, delays\n",
    "        delay = base_delay * (2 ** (attempt - 1))\n",
    "        delays.append(delay)\n",
    "        time.sleep(delay)\n",
    "\n",
    "print(retry_on_server_error(make_fake_call([503, 500, 200])))\n",
    "print(retry_on_server_error(make_fake_call([404])))\n",
    "print(retry_on_server_error(make_fake_call([503, 503, 503, 503])))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c7f4ec4b",
   "metadata": {},
   "source": [
    "## Response Contract Validation\n",
    "\n",
    "A response contract defines the keys and value types your code expects. Validate close to the API boundary so downstream analysis code receives clean, predictable data."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-c7f4ec4b",
   "metadata": {},
   "source": [
    "```{index} response contract, data validation\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "98d6ea40",
   "metadata": {},
   "source": [
    "### Worked Example: Validate Required Keys\n",
    "\n",
    "`parse_weather_response()` checks the response before using it. It raises a `ValueError` that names exactly which fields are missing, so a bad response fails at the API boundary with a clear message instead of deep inside later analysis code. The second call passes a payload without `windspeed` and shows the message the caller receives."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-98d6ea40",
   "metadata": {},
   "source": [
    "```{index} data validation\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "e02fd92a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-08-31T05:51:31.947530Z",
     "iopub.status.busy": "2026-08-31T05:51:31.947435Z",
     "iopub.status.idle": "2026-08-31T05:51:31.949640Z",
     "shell.execute_reply": "2026-08-31T05:51:31.949437Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'temperature': 21.4, 'windspeed': 13.2}\n",
      "Rejected: Missing weather fields: ['windspeed']\n"
     ]
    }
   ],
   "source": [
    "def parse_weather_response(payload):\n",
    "    if \"current_weather\" not in payload:\n",
    "        raise ValueError(\"Missing current_weather in API response\")\n",
    "\n",
    "    current = payload[\"current_weather\"]\n",
    "    required = [\"temperature\", \"windspeed\"]\n",
    "    missing = [key for key in required if key not in current]\n",
    "    if missing:\n",
    "        raise ValueError(f\"Missing weather fields: {missing}\")\n",
    "\n",
    "    return {\n",
    "        \"temperature\": current[\"temperature\"],\n",
    "        \"windspeed\": current[\"windspeed\"],\n",
    "    }\n",
    "\n",
    "print(parse_weather_response({\"current_weather\": {\"temperature\": 21.4, \"windspeed\": 13.2}}))\n",
    "\n",
    "try:\n",
    "    parse_weather_response({\"current_weather\": {\"temperature\": 21.4}})\n",
    "except ValueError as error:\n",
    "    print(\"Rejected:\", error)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "validation-types",
   "metadata": {},
   "source": [
    "This example checks only that the keys are present. A stricter contract also checks types, as the final exercise does with `isinstance()`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "17aecb84",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Validate a User Record\n",
    "#   Write `parse_user(payload)`. It checks for the keys \"id\", \"name\", and\n",
    "#   \"email\". If any are missing, it raises ValueError with the message\n",
    "#   \"Missing user fields: [...]\", listing the missing keys in that order.\n",
    "#   Otherwise it returns a new dict with only those three keys.\n",
    "#   Call it on `good_user`, then on `bad_user` inside try/except, and print\n",
    "#   \"Rejected:\" with the error message for the failure.\n",
    "#   Print exactly:\n",
    "#   {'id': 7, 'name': 'Ana', 'email': 'ana@example.test'}\n",
    "#   Rejected: Missing user fields: ['email']\n",
    "good_user = {\"id\": 7, \"name\": \"Ana\", \"email\": \"ana@example.test\", \"plan\": \"free\"}\n",
    "bad_user = {\"id\": 8, \"name\": \"Ben\"}\n",
    "### Your code starts here\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "350cc569",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'id': 7, 'name': 'Ana', 'email': 'ana@example.test'}\n",
      "Rejected: Missing user fields: ['email']\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "good_user = {\"id\": 7, \"name\": \"Ana\", \"email\": \"ana@example.test\", \"plan\": \"free\"}\n",
    "bad_user = {\"id\": 8, \"name\": \"Ben\"}\n",
    "\n",
    "def parse_user(payload):\n",
    "    required = [\"id\", \"name\", \"email\"]\n",
    "    missing = [key for key in required if key not in payload]\n",
    "    if missing:\n",
    "        raise ValueError(f\"Missing user fields: {missing}\")\n",
    "    return {key: payload[key] for key in required}\n",
    "\n",
    "print(parse_user(good_user))\n",
    "\n",
    "try:\n",
    "    parse_user(bad_user)\n",
    "except ValueError as error:\n",
    "    print(\"Rejected:\", error)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2be5034d",
   "metadata": {},
   "source": [
    "## Exercises\n",
    "\n",
    "This task combines pagination and response contract validation from this section."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "819e3ed5",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-08-31T05:51:31.950738Z",
     "iopub.status.busy": "2026-08-31T05:51:31.950659Z",
     "iopub.status.idle": "2026-08-31T05:51:31.952354Z",
     "shell.execute_reply": "2026-08-31T05:51:31.952139Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[]\n"
     ]
    }
   ],
   "source": [
    "### Exercise: Resilient Client\n",
    "#   `get_page` returns the pages of a page-based API, and `get_broken_page`\n",
    "#   returns the same pages except that page 2 has no \"items\" list.\n",
    "#   Complete `fetch_valid_pages(get_page_fn)` so it fetches every page,\n",
    "#   starting at page 1, and validates each page before using it. Raise\n",
    "#   ValueError with \"Page <n> has no items list\" when \"items\" is missing or is\n",
    "#   not a list, and \"Page <n> has no next_page key\" when \"next_page\" is missing.\n",
    "#   Call it on `get_page`, then on `get_broken_page` inside try/except, and\n",
    "#   print \"Rejected:\" with the error message for the failure.\n",
    "#   Print exactly:\n",
    "#   ['a', 'b', 'c', 'd', 'e']\n",
    "#   Rejected: Page 2 has no items list\n",
    "pages = {\n",
    "    1: {\"items\": [\"a\", \"b\"], \"next_page\": 2},\n",
    "    2: {\"items\": [\"c\", \"d\"], \"next_page\": 3},\n",
    "    3: {\"items\": [\"e\"], \"next_page\": None},\n",
    "}\n",
    "broken_pages = {**pages, 2: {\"next_page\": 3}}\n",
    "\n",
    "def get_page(page_number):\n",
    "    return pages[page_number]\n",
    "\n",
    "def get_broken_page(page_number):\n",
    "    return broken_pages[page_number]\n",
    "\n",
    "def fetch_valid_pages(get_page_fn):\n",
    "    items = []\n",
    "    page = 1\n",
    "    while page is not None:\n",
    "        payload = get_page_fn(page)\n",
    "        ### Your code starts here\n",
    "        page = None\n",
    "        ### Your code ends here\n",
    "    return items\n",
    "\n",
    "print(fetch_valid_pages(get_page))\n",
    "\n",
    "try:\n",
    "    fetch_valid_pages(get_broken_page)\n",
    "except ValueError as error:\n",
    "    print(\"Rejected:\", error)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "daa991e6",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-08-31T05:51:31.953288Z",
     "iopub.status.busy": "2026-08-31T05:51:31.953227Z",
     "iopub.status.idle": "2026-08-31T05:51:31.955139Z",
     "shell.execute_reply": "2026-08-31T05:51:31.954954Z"
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['a', 'b', 'c', 'd', 'e']\n",
      "Rejected: Page 2 has no items list\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "pages = {\n",
    "    1: {\"items\": [\"a\", \"b\"], \"next_page\": 2},\n",
    "    2: {\"items\": [\"c\", \"d\"], \"next_page\": 3},\n",
    "    3: {\"items\": [\"e\"], \"next_page\": None},\n",
    "}\n",
    "broken_pages = {**pages, 2: {\"next_page\": 3}}\n",
    "\n",
    "def get_page(page_number):\n",
    "    return pages[page_number]\n",
    "\n",
    "def get_broken_page(page_number):\n",
    "    return broken_pages[page_number]\n",
    "\n",
    "def fetch_valid_pages(get_page_fn):\n",
    "    items = []\n",
    "    page = 1\n",
    "    while page is not None:\n",
    "        payload = get_page_fn(page)\n",
    "        if not isinstance(payload.get(\"items\"), list):\n",
    "            raise ValueError(f\"Page {page} has no items list\")\n",
    "        if \"next_page\" not in payload:\n",
    "            raise ValueError(f\"Page {page} has no next_page key\")\n",
    "        items.extend(payload[\"items\"])\n",
    "        page = payload[\"next_page\"]\n",
    "    return items\n",
    "\n",
    "print(fetch_valid_pages(get_page))\n",
    "\n",
    "try:\n",
    "    fetch_valid_pages(get_broken_page)\n",
    "except ValueError as error:\n",
    "    print(\"Rejected:\", error)"
   ]
  }
 ],
 "metadata": {
  "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.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
