{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "3ca7087e",
   "metadata": {},
   "source": [
    "# API Fundamentals: GET, Params, and Error Handling"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "cea645e5",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-08-31T05:51:27.378364Z",
     "iopub.status.busy": "2026-08-31T05:51:27.378166Z",
     "iopub.status.idle": "2026-08-31T05:51:27.428606Z",
     "shell.execute_reply": "2026-08-31T05:51:27.428319Z"
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "import json\n",
    "from urllib.parse import urlparse, parse_qs\n",
    "\n",
    "import requests"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "65833a19",
   "metadata": {},
   "source": [
    "Web APIs let Python programs request data from services over HTTP. In data work, an API is often the difference between copying a file by hand and writing a repeatable data collection step. This section focuses on read-only API calls: choosing an endpoint, passing query parameters, reading JSON, and handling errors without crashing a larger analysis."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9b0d9a87",
   "metadata": {},
   "source": [
    "```{contents}\n",
    ":local:\n",
    ":depth: 2\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c067c91d",
   "metadata": {},
   "source": [
    "## What Is an API?\n",
    "\n",
    "An application programming interface (**API**) is a defined way for one program to request a service from another program. You have already used several kinds. In each case, you follow the documented rules for making a request and never need to see how the work is done. \n",
    "- A library API is the set of functions and classes a package provides, such as `math.sqrt()` or the methods of a pandas DataFrame. \n",
    "- An operating system API lets a program ask the system to open a file, read the clock, or draw a window, which is what `open()` does on your behalf. \n",
    "- A database API lets a program send queries and receive rows. \n",
    " \n",
    "\n",
    "A web API applies the same idea across a network. The program making the request is the client, and the program that answers is the server. They communicate using HTTP (Hypertext Transfer Protocol), the same protocol browsers use to load web pages. Most web APIs follow a convention called **REST**, in which each URL identifies a resource, such as a customer or a weather forecast, and the HTTP method indicates what action the client wants to take on it.\n",
    "\n",
    "\n",
    "\n",
    "Method | Purpose | Example request | Typical success | Safe | Idempotent |\n",
    "|---|---|---|---|---|---|\n",
    "| **`GET`** | Retrieve one resource or a list | `GET /weather?city=Rolla` | `200 OK` | Yes | Yes |\n",
    "| `POST` | Create a resource or submit data for processing | `POST /saved-cities` with `{\"city\": \"Rolla\"}` | `201 Created` | No | No |\n",
    "| `PUT` | Create or replace a whole resource | `PUT /saved-cities/42` with the full record | `200 OK`, `204 No Content`, or `201 Created` | No | Yes |\n",
    "| `PATCH` | Change part of a resource | `PATCH /saved-cities/42` with `{\"units\": \"celsius\"}` | `200 OK` or `204 No Content` | No | Not guaranteed |\n",
    "| `DELETE` | Remove a resource | `DELETE /saved-cities/42` | `204 No Content` | No | Yes |\n",
    "\n",
    "A **safe** method does not request changes to server state; incidental effects, such as request logging, may still occur. An **idempotent** (*idem*, \"same\"; *potent*, \"power\") method has the same intended effect on the server whether you send the same request once or several times: deleting record 42 twice still leaves it deleted, but posting the same city twice can create two saved records.\n",
    "\n",
    "Idempotence describes the effect on the server, not the response. The first `DELETE` might return 204 No Content, while a repeat returns 404 Not Found. The distinction matters when a request times out and your code retries it, which [12.2 API Reliability](1202-api-reliability.ipynb) covers. \n",
    "\n",
    "A REST API documentation also mentions two more methods, both safe and idempotent: `HEAD` works like `GET` but returns only the response headers, and `OPTIONS` asks which methods an endpoint accepts.\n",
    "\n",
    "This section uses only `GET`. The other methods appear here so you can read API documentation, and they return in the next section."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-c067c91d",
   "metadata": {},
   "source": [
    "```{index} API, REST API, HTTP method, safe method, idempotent\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b304d368",
   "metadata": {},
   "source": [
    "Every HTTP response begins with a status code, a three-digit number the server uses to report how the request went. Your code should check it before trusting anything else in the response, because a server can send back a well-formed body that describes an error instead of the data you asked for. You have probably seen one already: `404 Not Found`, the code behind a broken link.\n",
    "\n",
    "The first digit gives the category, and it tells you who needs to act. A code starting with 2 means the request succeeded. A code starting with 4 means something was wrong with the request, so sending it again unchanged will fail the same way. A code starting with 5 means the server failed on a valid request, so trying again later may work. You do not need to memorize individual codes; knowing the ranges is enough to decide what to do next:\n",
    "\n",
    "| Code range | Meaning | Typical action |\n",
    "|---|---|---|\n",
    "| `2xx` | Success | Parse the response |\n",
    "| `3xx` | Redirect | Usually handled by the client library |\n",
    "| `4xx` | Client-side problem | Check the endpoint, parameters, or authentication; for 429 Too Many Requests, wait and retry |\n",
    "| `5xx` | Server-side problem | Retry later or report failure gracefully |\n",
    "\n",
    "A useful habit is to describe every API call as **endpoint** + **method** + **parameters** + **expected response shape**."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b110ce9c",
   "metadata": {},
   "source": [
    "### Worked Example: Read an API Contract\n",
    "\n",
    "[Open-Meteo](https://open-meteo.com/en/docs) is a free weather API that needs no key. Its documentation describes a request for the current weather like this:\n",
    "\n",
    "| # | Field | Value |\n",
    "| - |---|---|\n",
    "| 1 | Endpoint | `https://api.open-meteo.com/v1/forecast` |\n",
    "| 2 | Method | `GET` |\n",
    "| 3 | Required params | `latitude`, `longitude` |\n",
    "| 4 | Optional param used here | `current_weather=true` |\n",
    "| 5 | Response | JSON object with `latitude`, `longitude`, and a nested `current_weather` object that holds `temperature`, `windspeed`, and more |\n",
    "\n",
    "Before writing code, identify the smallest successful request and the keys your code expects back."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-b110ce9c",
   "metadata": {},
   "source": [
    "```{index} API contract, API endpoint, Open-Meteo API\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "849b9fff",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-08-31T05:51:27.430129Z",
     "iopub.status.busy": "2026-08-31T05:51:27.430038Z",
     "iopub.status.idle": "2026-08-31T05:51:27.432104Z",
     "shell.execute_reply": "2026-08-31T05:51:27.431916Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "GET https://api.open-meteo.com/v1/forecast\n",
      "Required params: latitude, longitude\n",
      "Expected keys: latitude, longitude, current_weather\n"
     ]
    }
   ],
   "source": [
    "api_contract = {\n",
    "    \"endpoint\": \"https://api.open-meteo.com/v1/forecast\",\n",
    "    \"method\": \"GET\",\n",
    "    \"required_params\": [\"latitude\", \"longitude\"],\n",
    "    \"response_keys\": [\"latitude\", \"longitude\", \"current_weather\"],\n",
    "}\n",
    "\n",
    "print(api_contract[\"method\"], api_contract[\"endpoint\"])\n",
    "print(\"Required params:\", \", \".join(api_contract[\"required_params\"]))\n",
    "print(\"Expected keys:\", \", \".join(api_contract[\"response_keys\"]))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "75715142",
   "metadata": {},
   "source": [
    "You can check the contract against the live service. The cell below sends the smallest successful request for Rolla, Missouri, with `requests.get()` from the next section, and compares the keys that come back with the contract. It runs on its own, needs an internet connection, and is skipped when the book builds, so press Run to see a live response. If the request fails, it prints a message instead of an error."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5d4ba396",
   "metadata": {
    "tags": [
     "skip-execution"
    ]
   },
   "outputs": [],
   "source": [
    "import requests\n",
    "\n",
    "try:\n",
    "    response = requests.get(\n",
    "        api_contract[\"endpoint\"],\n",
    "        params={\"latitude\": 37.95, \"longitude\": -91.77, \"current_weather\": \"true\"},\n",
    "        timeout=10,\n",
    "    )\n",
    "    response.raise_for_status()\t# checks the status code of a response: 2xx, ...\n",
    "    live = response.json()\t\t\n",
    "    print(\"Top-level keys:\", \", \".join(sorted(live)))\n",
    "    print(\"Contract keys present:\", all(key in live for key in api_contract[\"response_keys\"]))\n",
    "    print(\"Current temperature:\", live[\"current_weather\"][\"temperature\"],\n",
    "          live[\"current_weather_units\"][\"temperature\"])\n",
    "\n",
    "except requests.RequestException as error:\n",
    "    print(\"Request failed:\", error)\n",
    "\n",
    "\n",
    "### response.raise_for_status() checks the response’s status code and raises an exception if it signals an error (4xx or 5xx).\n",
    "### response.json() takes the body of the response, which arrives as JSON text, and converts it into ordinary Python objects, so live is a dictionary you can index."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "409b7012",
   "metadata": {},
   "source": [
    "A run in November 2026 printed the lines below. The contract keys are all there, along with extras such as `timezone` and `current_weather_units` that this request does not need. Your temperature will differ.\n",
    "\n",
    "```text\n",
    "Top-level keys: current_weather, current_weather_units, elevation, generationtime_ms, latitude, longitude, timezone, timezone_abbreviation, utc_offset_seconds\n",
    "Contract keys present: True\n",
    "Current temperature: 7.5 °C\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f2e71524",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Describe an Endpoint\n",
    "#   The documentation for a forecast endpoint says: send a GET request to\n",
    "#   https://api.example.test/forecast with the required parameters `city` and\n",
    "#   `days`; the response is a JSON object with the keys `city` and `daily`.\n",
    "#   Build a dictionary `forecast_contract` with the keys \"endpoint\", \"method\",\n",
    "#   \"required_params\", and \"response_keys\", as in the worked example, and print\n",
    "#   it in the same three-line format.\n",
    "#   Print exactly:\n",
    "#   GET https://api.example.test/forecast\n",
    "#   Required params: city, days\n",
    "#   Expected keys: city, daily\n",
    "### Your code starts here\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "75ffcf8e",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "GET https://api.example.test/forecast\n",
      "Required params: city, days\n",
      "Expected keys: city, daily\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "forecast_contract = {\n",
    "    \"endpoint\": \"https://api.example.test/forecast\",\n",
    "    \"method\": \"GET\",\n",
    "    \"required_params\": [\"city\", \"days\"],\n",
    "    \"response_keys\": [\"city\", \"daily\"],\n",
    "}\n",
    "\n",
    "print(forecast_contract[\"method\"], forecast_contract[\"endpoint\"])\n",
    "print(\"Required params:\", \", \".join(forecast_contract[\"required_params\"]))\n",
    "print(\"Expected keys:\", \", \".join(forecast_contract[\"response_keys\"]))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "32971b3b",
   "metadata": {},
   "source": [
    "## Making GET Requests with `requests`\n",
    "\n",
    "The [`requests`](https://requests.readthedocs.io/) library is the common Python tool for HTTP. A basic `GET` request looks like this:\n",
    "\n",
    "```python\n",
    "response = requests.get(url, timeout=10)\n",
    "response.raise_for_status()\n",
    "data = response.json()\n",
    "```\n",
    "\n",
    "`requests` provides a convenience function for each common HTTP method (`get`, `post`, `put`, `patch`, `delete`, `head`, `options`). Each is a thin wrapper around the general `requests.request(method, url, **kwargs)`, so `requests.get(url)` is equivalent to `requests.request(\"GET\", url)`.\n",
    "\n",
    "The cell below sends the same GET request both ways to httpbin.org, a free service that echoes back what it receives, and compares the results. It calls a live service, so the book skips it during the build; run it yourself. If the request fails, it prints a message instead of an error."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-32971b3b",
   "metadata": {},
   "source": [
    "```{index} GET request, requests library, requests.get()\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "670bc032",
   "metadata": {
    "tags": [
     "skip-execution"
    ]
   },
   "outputs": [],
   "source": [
    "import requests\n",
    "\n",
    "url = \"https://httpbin.org/get\"\n",
    "params = {\"q\": \"python\"}\n",
    "\n",
    "try:\n",
    "    r1 = requests.get(url, params=params, timeout=10)\n",
    "    r2 = requests.request(\"GET\", url, params=params, timeout=10)\n",
    "    \n",
    "    r1.raise_for_status()\n",
    "    r2.raise_for_status()\n",
    "    \n",
    "    print(\"r1:\", r1.request.method, r1.url, r1.status_code)\n",
    "    print(\"r2:\", r2.request.method, r2.url, r2.status_code)\n",
    "    print(\"Server saw the same query:\", r1.json()[\"args\"] == r2.json()[\"args\"])\n",
    "    print(\"Separate response objects:\", r1 is not r2)\n",
    "\n",
    "except requests.RequestException as error:\n",
    "    print(\"No live connection:\", error)\n",
    "    \n",
    "    \n",
    "### .json() parses the response body into a dictionary, and [\"args\"] immediately pulls out the value stored under the key \"args\"."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a77c1330",
   "metadata": {},
   "source": [
    "A run in November 2026 printed:\n",
    "\n",
    "```text\n",
    "r1: GET https://httpbin.org/get?q=python 200\n",
    "r2: GET https://httpbin.org/get?q=python 200\n",
    "Server saw the same query: True\n",
    "```\n",
    "\n",
    "Both calls built the same URL, and the server received the same query, but each call sent a separate request and returned its own response object."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "stand-ins-text",
   "metadata": {},
   "source": [
    "The core examples in this chapter use stand-ins instead of the network, so they run the same way every time, online or not. A few optional cells, such as the contract check at the start of this section and the httpbin comparison above, call a real service. The book skips them when it builds, so run them yourself to see a live response."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f9107413",
   "metadata": {},
   "source": [
    "### Worked Example: Parse a JSON Response\n",
    "\n",
    "This example uses a small stand-in for a `requests` response, so it runs without a network connection. The stand-in has the same `raise_for_status()` and `.json()` methods as a real response, so the parsing code is exactly what you would write against a live API."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-f9107413",
   "metadata": {},
   "source": [
    "```{index} JSON, response.json()\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "cda257f7",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-08-31T05:51:27.433275Z",
     "iopub.status.busy": "2026-08-31T05:51:27.433207Z",
     "iopub.status.idle": "2026-08-31T05:51:27.435325Z",
     "shell.execute_reply": "2026-08-31T05:51:27.435116Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Rolla: 72.5 degrees fahrenheit\n"
     ]
    }
   ],
   "source": [
    "import requests\n",
    "\n",
    "class DemoResponse:\n",
    "    def __init__(self, payload, status_code=200):\n",
    "        self._payload = payload\n",
    "        self.status_code = status_code\n",
    "\n",
    "    def raise_for_status(self):\n",
    "        if self.status_code >= 400:\n",
    "            raise requests.HTTPError(f\"HTTP {self.status_code}\")\n",
    "\n",
    "    def json(self):\n",
    "        return self._payload\n",
    "\n",
    "response = DemoResponse({\"city\": \"Rolla\", \"temperature\": 72.5, \"units\": \"fahrenheit\"})\n",
    "response.raise_for_status()\n",
    "data = response.json()\n",
    "\n",
    "print(f\"{data['city']}: {data['temperature']} degrees {data['units']}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dd910cfd",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Read a Response\n",
    "#   Use `DemoResponse`, the stand-in from the worked example above. Create\n",
    "#   `response` from `city_payload`, call `raise_for_status()`, and parse the\n",
    "#   body with `.json()`. Then print how many cities the payload lists and the\n",
    "#   name of the first one.\n",
    "#   Print exactly:\n",
    "#   3 cities\n",
    "#   First: Rolla\n",
    "city_payload = {\"results\": [{\"name\": \"Rolla\"}, {\"name\": \"Austin\"}, {\"name\": \"Boston\"}]}\n",
    "### Your code starts here\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "0df61815",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3 cities\n",
      "First: Rolla\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "city_payload = {\"results\": [{\"name\": \"Rolla\"}, {\"name\": \"Austin\"}, {\"name\": \"Boston\"}]}\n",
    "\n",
    "response = DemoResponse(city_payload)\n",
    "response.raise_for_status()\n",
    "data = response.json()\n",
    "\n",
    "print(len(data[\"results\"]), \"cities\")\n",
    "print(\"First:\", data[\"results\"][0][\"name\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "json-text-objects",
   "metadata": {},
   "source": [
    "## JSON Text and Python Objects\n",
    "\n",
    "An API sends its response body over the network as text. **JSON** (JavaScript Object Notation) looks a lot like Python dictionary and list literals, but until something parses it, a JSON body is just a string. The standard library `json` module converts in both directions:\n",
    "\n",
    "| Function | Input | Output |\n",
    "|---|---|---|\n",
    "| `json.loads(text)` | A JSON string | Python `dict`, `list`, `str`, `int`, `float`, `bool`, or `None` |\n",
    "| `json.dumps(obj)` | A Python `dict`, `list`, or other basic value | A JSON string |\n",
    "\n",
    "The `s` at the end of each name stands for *string*. Turning Python objects into JSON text is called **JSON serialization**, and parsing the text back is deserialization. `response.json()` is a shortcut for the parsing step: it takes the response body text and calls `json.loads()` on it for you. When JSON text comes from somewhere other than a `requests` response, such as a saved string, a log line, or a cache, you call `json.loads()` yourself."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "response-body-attrs",
   "metadata": {},
   "source": [
    "A response gives you three ways to read its body:\n",
    "\n",
    "| Attribute | Gives you | Use for |\n",
    "|---|---|---|\n",
    "| `response.text` | The body as a `str` | Looking at the raw text, HTML pages |\n",
    "| `response.content` | The body as `bytes` | Images, files, anything binary |\n",
    "| `response.json()` | The body parsed into a `dict` or `list` | JSON APIs |\n",
    "\n",
    "`response.json()` is a method, so it needs the parentheses; `response.text` and `response.content` are plain attributes. Calling `response.json()` gives the same result as `json.loads(response.text)`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "json-python-spelling",
   "metadata": {},
   "source": [
    "JSON and Python spell a few values differently:\n",
    "\n",
    "| JSON | Python |\n",
    "|---|---|\n",
    "| `\"text\"` (double quotes only) | `'text'` or `\"text\"` |\n",
    "| `true`, `false` | `True`, `False` |\n",
    "| `null` | `None` |\n",
    "| number | `int` or `float` |\n",
    "| object `{...}` | `dict` |\n",
    "| array `[...]` | `list` |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-json-text-objects",
   "metadata": {},
   "source": [
    "```{index} json.loads(), json.dumps(), JSON serialization\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "json-text-example",
   "metadata": {},
   "source": [
    "### Worked Example: Parse JSON Text by Hand\n",
    "\n",
    "The string below stands in for a response body. It contains `false` and `null`, so it is valid JSON but not valid Python. After `json.loads()`, you work with an ordinary dictionary, and `.get()` supplies a default for a key the payload does not include."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "json-loads-demo",
   "metadata": {
    "execution": {
     "iopub.status.busy": "2026-10-11T20:27:42.983094Z",
     "iopub.execute_input": "2026-10-11T20:27:42.983149Z",
     "shell.execute_reply": "2026-10-11T20:27:42.984438Z",
     "iopub.status.idle": "2026-10-11T20:27:42.984595Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'str'>\n",
      "<class 'dict'>\n",
      "False None\n",
      "not reported\n"
     ]
    }
   ],
   "source": [
    "import json\n",
    "\n",
    "raw_body = '{\"city\": \"Rolla\", \"temperature\": 72.5, \"raining\": false, \"alerts\": null}'\n",
    "print(type(raw_body))\n",
    "\n",
    "weather = json.loads(raw_body)\n",
    "print(type(weather))\n",
    "print(weather[\"raining\"], weather[\"alerts\"])\n",
    "print(weather.get(\"humidity\", \"not reported\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "json-dumps-text",
   "metadata": {},
   "source": [
    "Going the other way, `json.dumps()` turns a Python object into JSON text, for example to log a summary, save it to a file, or send it in a request body. In the output, `False` becomes `false`, `None` becomes `null`, and every string uses double quotes. Parsing that text again gives back an equal dictionary."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "json-dumps-demo",
   "metadata": {
    "execution": {
     "iopub.status.busy": "2026-10-11T20:27:42.985310Z",
     "iopub.execute_input": "2026-10-11T20:27:42.985374Z",
     "iopub.status.idle": "2026-10-11T20:27:42.986653Z",
     "shell.execute_reply": "2026-10-11T20:27:42.986476Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\"city\": \"Rolla\", \"raining\": false, \"alerts\": null}\n",
      "<class 'str'>\n",
      "True\n"
     ]
    }
   ],
   "source": [
    "summary = {\"city\": weather[\"city\"], \"raining\": weather[\"raining\"], \"alerts\": weather[\"alerts\"]}\n",
    "summary_text = json.dumps(summary)\n",
    "\n",
    "print(summary_text)\n",
    "print(type(summary_text))\n",
    "print(json.loads(summary_text) == summary)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "json-roundtrip-question",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ],
    "execution": {
     "iopub.status.busy": "2026-10-11T20:27:42.987368Z",
     "iopub.execute_input": "2026-10-11T20:27:42.987418Z",
     "shell.execute_reply": "2026-10-11T20:27:42.988420Z",
     "iopub.status.idle": "2026-10-11T20:27:42.988595Z"
    }
   },
   "outputs": [],
   "source": [
    "### Exercise: JSON Round Trip\n",
    "#   `request_options` is a Python dictionary that a program wants to store as\n",
    "#   JSON text. Before you run any code, predict how `False` and `None` will\n",
    "#   appear in the JSON text. Then convert the dictionary to a JSON string named\n",
    "#   `options_text` with `json.dumps()` and print it. Finally, parse\n",
    "#   `options_text` with `json.loads()` and print whether the result equals\n",
    "#   `request_options`.\n",
    "#   Print exactly:\n",
    "#   {\"city\": \"Rolla\", \"units\": \"metric\", \"include_alerts\": false, \"max_days\": 3, \"station\": null}\n",
    "#   True\n",
    "request_options = {\"city\": \"Rolla\", \"units\": \"metric\", \"include_alerts\": False, \"max_days\": 3, \"station\": None}\n",
    "\n",
    "### Your code starts here\n",
    "\n",
    "### Your code ends here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "json-roundtrip-solution",
   "metadata": {
    "tags": [
     "hide-input"
    ],
    "execution": {
     "iopub.status.busy": "2026-10-11T20:27:42.989293Z",
     "iopub.execute_input": "2026-10-11T20:27:42.989344Z",
     "iopub.status.idle": "2026-10-11T20:27:42.990606Z",
     "shell.execute_reply": "2026-10-11T20:27:42.990446Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\"city\": \"Rolla\", \"units\": \"metric\", \"include_alerts\": false, \"max_days\": 3, \"station\": null}\n",
      "True\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "request_options = {\"city\": \"Rolla\", \"units\": \"metric\", \"include_alerts\": False, \"max_days\": 3, \"station\": None}\n",
    "\n",
    "options_text = json.dumps(request_options)\n",
    "print(options_text)\n",
    "print(json.loads(options_text) == request_options)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9ffda365",
   "metadata": {},
   "source": [
    "## Query Parameters\n",
    "\n",
    "Many `GET` endpoints use **query parameters**: key/value pairs after the `?` in a URL. Build them with the `params=` argument instead of manually concatenating strings. `requests` handles escaping spaces, punctuation, and special characters correctly."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-9ffda365",
   "metadata": {},
   "source": [
    "```{index} query parameter, URL encoding\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "75e5f2a3",
   "metadata": {},
   "source": [
    "### Worked Example: Build a Request URL Safely\n",
    "\n",
    "Instead of sending the request, this example prepares it and prints the URL that `requests` builds from `params=`. Notice that the space in `New York` is encoded for you, and that parsing the query string recovers the original values."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-75e5f2a3",
   "metadata": {},
   "source": [
    "```{index} prepared request, urlparse()\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "4e7d59e2",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-08-31T05:51:27.436419Z",
     "iopub.status.busy": "2026-08-31T05:51:27.436353Z",
     "iopub.status.idle": "2026-08-31T05:51:27.438188Z",
     "shell.execute_reply": "2026-08-31T05:51:27.437994Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "https://api.example.test/weather?city=New+York&units=fahrenheit\n",
      "{'city': ['New York'], 'units': ['fahrenheit']}\n"
     ]
    }
   ],
   "source": [
    "from urllib.parse import urlparse, parse_qs\t\t# “parse query string”\n",
    "\n",
    "import requests\n",
    "\n",
    "base_url = \"https://api.example.test/weather\"\n",
    "params = {\"city\": \"New York\", \"units\": \"fahrenheit\"}\n",
    "\n",
    "request = requests.Request(\"GET\", base_url, params=params).prepare()\n",
    "print(request.url)\n",
    "\n",
    "parsed = urlparse(request.url)\n",
    "print(parse_qs(parsed.query))\n",
    "\n",
    "\n",
    "### .prepare() builds the final, ready-to-send version of a request without sending it."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "url-encoding-text",
   "metadata": {},
   "source": [
    "Behind `params=`, `requests` performs **URL encoding**, also called *percent-encoding*: a character with special meaning in a URL is replaced by `%` followed by its byte value in hexadecimal. The standard library function `urllib.parse.urlencode()` does the same job for a whole dictionary, and `urllib.parse.quote()` encodes a single value. A space becomes `+` in `urlencode()` output and `%20` in `quote()` output, and servers read both as a space in a query string. Characters such as `&` and `=` are escaped as `%26` and `%3D`, so a value that contains them cannot split the query string into extra parameters. The first line below joins raw values by hand and shows the problem: the server would read `fish & chips` as two parameters. You rarely call these functions yourself, because `requests` does this for you with `params=`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-url-encoding-text",
   "metadata": {},
   "source": [
    "```{index} urllib.parse.urlencode(), urllib.parse.quote(), percent-encoding\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "url-encoding-demo",
   "metadata": {
    "execution": {
     "iopub.status.busy": "2026-10-11T20:27:42.993668Z",
     "iopub.execute_input": "2026-10-11T20:27:42.993720Z",
     "iopub.status.idle": "2026-10-11T20:27:42.995232Z",
     "shell.execute_reply": "2026-10-11T20:27:42.995056Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "q=fish & chips&filter=price=low&city=New York\n",
      "q=fish+%26+chips&filter=price%3Dlow&city=New+York\n",
      "fish%20%26%20chips\n"
     ]
    }
   ],
   "source": [
    "from urllib.parse import urlencode, quote\n",
    "\n",
    "search_params = {\"q\": \"fish & chips\", \"filter\": \"price=low\", \"city\": \"New York\"}\n",
    "\n",
    "naive = \"&\".join(f\"{key}={value}\" for key, value in search_params.items())\n",
    "print(naive)\n",
    "print(urlencode(search_params))\n",
    "print(quote(\"fish & chips\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "34af6b67",
   "metadata": {},
   "source": [
    "Every parameter value ends up as text in the URL. `requests` turns a Python `True` into the text `True`, but most web APIs, Open-Meteo included, document the lowercase JSON spelling `true`. That is why the Open-Meteo request at the start of this section passes `\"current_weather\": \"true\"` as a string."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "b9d68c9e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-08-31T05:51:27.439158Z",
     "iopub.status.busy": "2026-08-31T05:51:27.439095Z",
     "iopub.status.idle": "2026-08-31T05:51:27.440626Z",
     "shell.execute_reply": "2026-08-31T05:51:27.440448Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "https://api.example.test/search\n"
     ]
    }
   ],
   "source": [
    "### Exercise: Query Parameters\n",
    "#   The endpoint https://api.example.test/search accepts `q`, `page`, and\n",
    "#   `limit`. Create a prepared GET request for page 2 of a search for\n",
    "#   `python api`, limited to 5 results, and print the final URL.\n",
    "#   Print exactly:\n",
    "#   https://api.example.test/search?q=python+api&page=2&limit=5\n",
    "### Your code starts here\n",
    "search_url = \"https://api.example.test/search\"\n",
    "params = {\n",
    "    # Fill in q, page, and limit.\n",
    "}\n",
    "\n",
    "prepared = requests.Request(\"GET\", search_url, params=params).prepare()\n",
    "print(prepared.url)\n",
    "### Your code ends here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "fd1fac2e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-08-31T05:51:27.441553Z",
     "iopub.status.busy": "2026-08-31T05:51:27.441492Z",
     "iopub.status.idle": "2026-08-31T05:51:27.443105Z",
     "shell.execute_reply": "2026-08-31T05:51:27.442917Z"
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "https://api.example.test/search?q=python+api&page=2&limit=5\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "search_url = \"https://api.example.test/search\"\n",
    "params = {\"q\": \"python api\", \"page\": 2, \"limit\": 5}\n",
    "\n",
    "prepared = requests.Request(\"GET\", search_url, params=params).prepare()\n",
    "print(prepared.url)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c48b56c9",
   "metadata": {},
   "source": [
    "## Error Handling\n",
    "\n",
    "Two categories of errors matter in most API code:\n",
    "\n",
    "1. **Network errors**: timeouts, DNS failures, broken connections, or other exceptions raised before a response arrives.\n",
    "2. **HTTP errors**: the server responds, but the status code signals a problem, such as `404 Not Found` or `500 Internal Server Error`.\n",
    "\n",
    "A reliable API helper should use a timeout, call `raise_for_status()`, and return a predictable value when the request fails."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-c48b56c9",
   "metadata": {},
   "source": [
    "```{index} HTTP status code, HTTPError, request timeout\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "73de1236",
   "metadata": {},
   "source": [
    "### Worked Example: Safe JSON Fetching\n",
    "\n",
    "This example wraps both failure checks in one function. `raise_for_status()` turns an error status into a `requests.HTTPError`, and `.json()` raises a `ValueError` when the body is not valid JSON, for example when a server under maintenance returns an HTML page instead. `TextResponse` extends the stand-in with a raw text body, as a real response has, so you can see that second case. Either way, the function returns `None` instead of crashing."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-73de1236",
   "metadata": {},
   "source": [
    "```{index} raise_for_status()\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "1fa3f7f5",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-08-31T05:51:27.444074Z",
     "iopub.status.busy": "2026-08-31T05:51:27.444006Z",
     "iopub.status.idle": "2026-08-31T05:51:27.445764Z",
     "shell.execute_reply": "2026-08-31T05:51:27.445586Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'results': ['a', 'b']}\n",
      "HTTP error: HTTP 404\n",
      "None\n",
      "Invalid JSON: Expecting value: line 1 column 1 (char 0)\n",
      "None\n"
     ]
    }
   ],
   "source": [
    "import json\n",
    "\n",
    "import requests\n",
    "\n",
    "class TextResponse(DemoResponse):\n",
    "    \"\"\"A response stand-in that holds the raw body text, like a real response.\"\"\"\n",
    "\n",
    "    def __init__(self, text, status_code=200):\n",
    "        super().__init__(None, status_code)\n",
    "        self.text = text\n",
    "\n",
    "    def json(self):\n",
    "        return json.loads(self.text)\n",
    "\n",
    "def parse_json_response(response):\n",
    "    \"\"\"Return JSON data from a response-like object, or None if it fails.\"\"\"\n",
    "    try:\n",
    "        response.raise_for_status()\n",
    "        return response.json()\n",
    "    except requests.HTTPError as error:\n",
    "        print(\"HTTP error:\", error)\n",
    "    except ValueError as error:\n",
    "        print(\"Invalid JSON:\", error)\n",
    "    return None\n",
    "\n",
    "ok = DemoResponse({\"results\": [\"a\", \"b\"]}, status_code=200)\n",
    "missing = DemoResponse({\"message\": \"not found\"}, status_code=404)\n",
    "html_page = TextResponse(\"<html>Down for maintenance</html>\")\n",
    "\n",
    "print(parse_json_response(ok))\n",
    "print(parse_json_response(missing))\n",
    "print(parse_json_response(html_page))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "request-exception-text",
   "metadata": {},
   "source": [
    "### Catching Any Request Failure\n",
    "\n",
    "The `requests` library organizes its exceptions in a hierarchy. `requests.RequestException` is the base class, and about 20 specific errors inherit from it: \n",
    "\n",
    "- `requests.ConnectionError` (the server cannot be reached), \n",
    "- `requests.Timeout` (no reply arrives within the `timeout` limit), and \n",
    "- `requests.HTTPError` (raised by `raise_for_status()`). \n",
    "\n",
    "Such as:\n",
    "\n",
    "```python\n",
    "class ConnectionError(RequestException):\n",
    "    \"\"\"A Connection error occurred.\"\"\"\n",
    "```\n",
    "\n",
    "Because every one of them is a `RequestException`, the clause `except requests.RequestException` catches any request failure. Use it when your code handles every failure the same way, and catch a specific subclass such as `requests.HTTPError` first when one case needs its own handling.\n",
    "```python\n",
    "try:\n",
    "    response = requests.get(url, timeout=5)\n",
    "    response.raise_for_status()\n",
    "except requests.RequestException as error:\n",
    "    print(\"Request failed:\", error)\n",
    "```\n",
    "\n",
    "With a real response, a body that is not valid JSON makes `.json()` raise `requests.JSONDecodeError`, which is both a `ValueError` and a `RequestException`, so this clause catches it too. The `TextResponse` stand-in raises the standard library's `json.JSONDecodeError`, which is only a `ValueError`; that is why `parse_json_response()` catches `ValueError`.\n",
    "\n",
    "The stand-in function below raises `requests.Timeout` instead of making a real call, so you can watch the base class catch it without a network connection."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-request-exception-text",
   "metadata": {},
   "source": [
    "```{index} RequestException, requests.Timeout, requests.ConnectionError\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "request-exception-demo",
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "True\n",
      "True\n",
      "Timeout: No reply from https://api.example.test/data within 5 seconds\n",
      "None\n"
     ]
    }
   ],
   "source": [
    "import requests\n",
    "\n",
    "def fake_get(url, timeout):\n",
    "    \"\"\"Stand in for requests.get() by simulating a server that never replies.\"\"\"\n",
    "    raise requests.Timeout(f\"No reply from {url} within {timeout} seconds\")\n",
    "\n",
    "def safe_get(url):\n",
    "    try:\n",
    "        return fake_get(url, timeout=5)\n",
    "    except requests.RequestException as error:\n",
    "        print(f\"{type(error).__name__}: {error}\")\n",
    "        return None\n",
    "\n",
    "print(issubclass(requests.Timeout, requests.RequestException))\n",
    "print(issubclass(requests.HTTPError, requests.RequestException))\n",
    "print(safe_get(\"https://api.example.test/data\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "6d8ef6fc",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ok\n",
      "ok\n",
      "ok\n",
      "ok\n"
     ]
    }
   ],
   "source": [
    "### Exercise: Name the Failure\n",
    "#   Complete `describe_failure(call_fn)`. It calls `call_fn()` and returns\n",
    "#   \"ok\" when no exception occurs. Otherwise it returns \"timeout\" for\n",
    "#   `requests.Timeout`, \"http error\" for `requests.HTTPError`, and\n",
    "#   \"other request error\" for any other `requests.RequestException`.\n",
    "#   Order the `except` clauses so each specific subclass is caught before\n",
    "#   the base class.\n",
    "#   Print exactly:\n",
    "#   ok\n",
    "#   timeout\n",
    "#   http error\n",
    "#   other request error\n",
    "def succeed():\n",
    "    return {\"status\": \"ok\"}\n",
    "\n",
    "def time_out():\n",
    "    raise requests.Timeout(\"no reply\")\n",
    "\n",
    "def not_found():\n",
    "    raise requests.HTTPError(\"HTTP 404\")\n",
    "\n",
    "def refuse():\n",
    "    raise requests.ConnectionError(\"connection refused\")\n",
    "\n",
    "def describe_failure(call_fn):\n",
    "    ### Your code starts here\n",
    "    return \"ok\"\n",
    "    ### Your code ends here\n",
    "\n",
    "for call_fn in [succeed, time_out, not_found, refuse]:\n",
    "    print(describe_failure(call_fn))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "e471d471",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ok\n",
      "timeout\n",
      "http error\n",
      "other request error\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "def succeed():\n",
    "    return {\"status\": \"ok\"}\n",
    "\n",
    "def time_out():\n",
    "    raise requests.Timeout(\"no reply\")\n",
    "\n",
    "def not_found():\n",
    "    raise requests.HTTPError(\"HTTP 404\")\n",
    "\n",
    "def refuse():\n",
    "    raise requests.ConnectionError(\"connection refused\")\n",
    "\n",
    "def describe_failure(call_fn):\n",
    "    try:\n",
    "        call_fn()\n",
    "    except requests.Timeout:\n",
    "        return \"timeout\"\n",
    "    except requests.HTTPError:\n",
    "        return \"http error\"\n",
    "    except requests.RequestException:\n",
    "        return \"other request error\"\n",
    "    return \"ok\"\n",
    "\n",
    "for call_fn in [succeed, time_out, not_found, refuse]:\n",
    "    print(describe_failure(call_fn))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0098527b",
   "metadata": {},
   "source": [
    "## Exercises\n",
    "\n",
    "This task combines query parameters, JSON parsing, error handling, and nested payloads from this section."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "281e1576",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Weather Request Helper\n",
    "#   1. Prepare a GET request to https://api.open-meteo.com/v1/forecast with the\n",
    "#      params latitude=37.95, longitude=-91.77, and current_weather=\"true\", and\n",
    "#      print its URL.\n",
    "#   2. Write `weather_from_response(response)`. It parses the response with\n",
    "#      `parse_json_response()` from the Error Handling section and returns a\n",
    "#      dict with the temperature and wind speed. It returns None when parsing\n",
    "#      fails or when the payload has no \"current_weather\" key.\n",
    "#   3. Call it on the four `TextResponse` stand-ins below and print each result.\n",
    "#   Print exactly:\n",
    "#   https://api.open-meteo.com/v1/forecast?latitude=37.95&longitude=-91.77&current_weather=true\n",
    "#   {'temperature': 21.4, 'windspeed': 13.2}\n",
    "#   HTTP error: HTTP 503\n",
    "#   None\n",
    "#   Invalid JSON: Expecting value: line 1 column 1 (char 0)\n",
    "#   None\n",
    "#   None\n",
    "responses = [\n",
    "    TextResponse('{\"latitude\": 37.95, \"current_weather\": {\"temperature\": 21.4, \"windspeed\": 13.2}}'),\n",
    "    TextResponse('{\"reason\": \"busy\"}', status_code=503),\n",
    "    TextResponse(\"<html>Down for maintenance</html>\"),\n",
    "    TextResponse('{\"error\": \"Latitude must be in range of -90 to 90\"}'),\n",
    "]\n",
    "### Your code starts here\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "65bd8b01",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "https://api.open-meteo.com/v1/forecast?latitude=37.95&longitude=-91.77&current_weather=true\n",
      "{'temperature': 21.4, 'windspeed': 13.2}\n",
      "HTTP error: HTTP 503\n",
      "None\n",
      "Invalid JSON: Expecting value: line 1 column 1 (char 0)\n",
      "None\n",
      "None\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "responses = [\n",
    "    TextResponse('{\"latitude\": 37.95, \"current_weather\": {\"temperature\": 21.4, \"windspeed\": 13.2}}'),\n",
    "    TextResponse('{\"reason\": \"busy\"}', status_code=503),\n",
    "    TextResponse(\"<html>Down for maintenance</html>\"),\n",
    "    TextResponse('{\"error\": \"Latitude must be in range of -90 to 90\"}'),\n",
    "]\n",
    "\n",
    "params = {\"latitude\": 37.95, \"longitude\": -91.77, \"current_weather\": \"true\"}\n",
    "request = requests.Request(\"GET\", \"https://api.open-meteo.com/v1/forecast\", params=params).prepare()\n",
    "print(request.url)\n",
    "\n",
    "def weather_from_response(response):\n",
    "    payload = parse_json_response(response)\n",
    "    if payload is None or \"current_weather\" not in payload:\n",
    "        return None\n",
    "    current = payload[\"current_weather\"]\n",
    "    return {\"temperature\": current[\"temperature\"], \"windspeed\": current[\"windspeed\"]}\n",
    "\n",
    "for response in responses:\n",
    "    print(weather_from_response(response))"
   ]
  }
 ],
 "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
}
