16. APIs and web data
Much of the data you analyze does not start in a CSV file. It sits behind a web service: product prices in a shop system, weather forecasts, customer records in a CRM, predictions from a deployed model. This module teaches you to ask these services for data from Python, to handle their errors and limits, and to turn their answers into tidy records that pandas and scikit-learn can use. When no service exists, you scrape the data from a web page.
All network code on this page is real code that you can point at a real API. To keep every example reproducible and offline, the runnable steps answer each request from saved responses in data/api/.
What you will learn
Section titled “What you will learn”- Explain how HTTP works: URLs, query parameters, methods, headers, status codes and JSON bodies.
- Call a JSON API with
httpxandrequests, and run the same client code offline withhttpx.MockTransport. - Collect every page of a paginated API, and turn nested JSON into tidy records, a summary and a CSV file.
- Handle errors, timeouts and rate limits with status-aware retries, exponential backoff and the
Retry-Afterheader. - Keep API keys out of your code with environment variables and
.envfiles, and never print a secret. - Parse an HTML page with BeautifulSoup:
select,find_all, attributes and tables to CSV.
Prerequisites
Section titled “Prerequisites”- Nested dicts and lists, and JSON as a format: 04. Data structures.
- Exceptions,
try/exceptandassert: 06. Errors and debugging. pathlib,jsonandcsv: 07. Files and data formats.os.environ,collections,statisticsanddatetime: 09. Standard library power tools.- Generators: 10. Iterators and generators.
- Fakes, dependency injection, exponential backoff and the retry decorator: 11. Decorators and context managers.
- Type hints such as
dict[str, Any]andCallable: 12. Type hints.
Concepts
Section titled “Concepts”APIs: data that you request
Section titled “APIs: data that you request”An API (application programming interface) is a defined way for one program to ask another program for data or for an action. A web API answers over the web. Your script is the client: it sends a request. The other computer is the server: it sends a response.
Why use an API instead of a downloaded file? A script that requests the data can run again tomorrow and get fresh numbers. Nobody has to export a file by hand. Data teams pull sales from shop systems, weather from forecast services and labels from annotation tools this way. Deployed models are APIs too: module 44 serves a churn model behind an HTTP endpoint.
flowchart LR
A["Web API"] -->|"JSON response"| B["Python client<br/>httpx"]
B --> C["Tidy records<br/>list of dicts"]
C --> D["CSV or DataFrame"]
D --> E["Analysis<br/>or model"]
This module uses a fictional shop, Maple & Finch Market. Its API lives at https://api.example.com/v1. The domain example.com is reserved for documentation, so no real server answers there. The files in data/api/ are the responses that this API would send.
URLs, endpoints and query parameters
Section titled “URLs, endpoints and query parameters”A URL (uniform resource locator) is the address of a resource on the web. An API URL has four parts:
| Part | Example | Meaning |
|---|---|---|
| scheme | https |
the protocol; https is encrypted HTTP |
| host | api.example.com |
the server |
| path | /v1/products |
the resource on that server |
| query string | page=2&per_page=10 |
options for this request, after the ? |
An endpoint is one path that the API answers, such as /v1/products or /v1/users. The query string holds query parameters: name=value pairs joined by &. They filter, sort or page the result. The urllib.parse module of the standard library takes a URL apart:
from urllib.parse import parse_qs, urlencode, urlsplit
next_url = "https://api.example.com/v1/products?page=2&per_page=10"parts = urlsplit(next_url)print(parts.scheme, parts.netloc, parts.path, parts.query)print(parse_qs(parts.query))print(urlencode({"q": "rain jacket", "category": "Clothing", "page": 1}))https api.example.com /v1/products page=2&per_page=10{'page': ['2'], 'per_page': ['10']}q=rain+jacket&category=Clothing&page=1parse_qs() returns a list for each name, because a name can repeat (?tag=new&tag=sale). All values are strings: the URL is text. urlencode() builds a query string and percent-encodes special characters: it replaces them with codes that are safe in a URL, here the space with +. Never glue a query string together with f-strings. Pass a dict of parameters to the HTTP library and let it encode them.
HTTP requests and responses
Section titled “HTTP requests and responses”HTTP (HyperText Transfer Protocol) is the set of rules that clients and servers follow on the web. HTTPS is HTTP over an encrypted connection; APIs that need a key always use it.
Every exchange is one request and one response:
- The request has a method (what to do), a URL, headers (name–value metadata) and an optional body (the data sent).
- The response has a status code (how it went), headers and a body (the data returned).
sequenceDiagram
participant S as Python script
participant A as api.example.com
S->>A: GET /v1/products?page=1
A-->>S: 200 OK + JSON page 1
S->>A: GET /v1/products?page=2
A-->>S: 429 Too Many Requests, Retry-After: 30
Note over S: wait 30 seconds
S->>A: GET /v1/products?page=2
A-->>S: 200 OK + JSON page 2
The method says what the client wants. Data work mostly reads, so GET is the method you use most:
| Method | Purpose | Body | Safe | Idempotent | Data example |
|---|---|---|---|---|---|
GET |
read a resource | no | yes | yes | download a page of products |
POST |
create a resource or run an action | yes | no | no | submit an order, ask a model for a prediction |
PUT |
replace a resource | yes | no | yes | upload a full product record |
PATCH |
change part of a resource | yes | no | no | set stock to 0 |
DELETE |
remove a resource | no | no | yes | delete a test record |
A safe method does not change data on the server. An idempotent method has the same effect whether you send it once or five times (module 11). Idempotency decides what you may retry: a repeated GET is harmless, a repeated POST can create two orders.
Headers carry metadata. These are the ones you meet in data work:
| Header | Direction | Example | Meaning |
|---|---|---|---|
Accept |
request | application/json |
the format the client wants back |
Content-Type |
both | application/json |
the format of this message’s body |
Authorization |
request | Bearer mf_live_... |
the client’s credentials |
User-Agent |
request | maple-analytics/1.0 |
the name of the client program |
Retry-After |
response | 30 |
wait this many seconds before the next request |
X-RateLimit-Remaining |
response | 0 |
requests left in the current window (a common convention) |
Header names are case-insensitive: content-type and Content-Type are the same header.
Status codes
Section titled “Status codes”Module 03 met the HTTP status code, the three-digit number that says how a request went. The first digit gives its class. The standard library knows every code and its reason phrase:
from http import HTTPStatus
for code in [200, 201, 204, 304, 400, 401, 403, 404, 422, 429, 500, 503]: status = HTTPStatus(code) kind = {2: "success", 3: "redirect", 4: "client error", 5: "server error"} print(f"{code} {status.phrase:<22} {kind[code // 100]}")200 OK success201 Created success204 No Content success304 Not Modified redirect400 Bad Request client error401 Unauthorized client error403 Forbidden client error404 Not Found client error422 Unprocessable Content client error429 Too Many Requests client error500 Internal Server Error server error503 Service Unavailable server errorWhat your code does depends on the class:
| Class | Meaning | What the client does |
|---|---|---|
| 2xx | success | read the body (204 has no body) |
| 3xx | redirect or “not modified” | follow the new URL, or use the cached copy for 304 |
| 4xx | the request is wrong | fix the request; do not retry it unchanged (429 is the exception) |
| 5xx | the server failed | retry later with backoff |
401 Unauthorized means “no valid credentials”. 403 Forbidden means “valid credentials, but no permission”. 422 Unprocessable Content means “the JSON was valid, but a field is wrong”, for example a negative quantity. 429 Too Many Requests means that you hit a rate limit: the request was fine, only too early. Python 3.12 prints the older phrase Unprocessable Entity for 422; Python 3.13 uses the current name.
JSON bodies
Section titled “JSON bodies”Most APIs send and receive JSON, the text format from module 04. The response body is text, and json.loads() turns it into Python objects. Each JSON type maps to one Python type:
| JSON | Python | Example from products_page_1.json |
|---|---|---|
object {...} |
dict |
one product |
array [...] |
list |
"data", the list of products |
| string | str |
"name": "Wireless Earbuds" |
| number without a dot | int |
"stock": 92 |
| number with a dot | float |
"amount": 79.99 |
true / false |
True / False |
"in_stock": true |
null |
None |
"next": null on the last page |
JSON has no date type. Dates arrive as strings such as "2021-03-01"; convert them with date.fromisoformat() (module 09) when you need date arithmetic.
import jsonfrom pathlib import Path
API_DIR = Path("data/api")
page_1 = json.loads((API_DIR / "products_page_1.json").read_text(encoding="utf-8"))print(list(page_1))print(page_1["total"], page_1["total_pages"], page_1["next"])first = page_1["data"][0]print(first["id"], first["price"], type(first["in_stock"]))['page', 'per_page', 'total', 'total_pages', 'next', 'data']30 3 https://api.example.com/v1/products?page=2&per_page=10P001 {'amount': 79.99, 'currency': 'USD'} <class 'bool'>The page is a dict with metadata (page, total, next) and the records in data. This wrapper shape is very common. Some APIs send a bare list instead, as users.json does.
To send JSON, you turn a Python object into text with json.dumps(). HTTP libraries do this for you when you pass json=..., and they set the Content-Type: application/json header too.
From nested JSON to tidy records
Section titled “From nested JSON to tidy records”API records are nested: a product has a price object and a rating object inside it. Analysis tools want tidy data: one row per observation, one column per variable and one value per cell. For a product list, one row is one product, and price.amount becomes a column price_amount.
The step from nested to tidy is called flattening (module 04). A short recursive function flattens any depth:
from typing import Any
def flatten(record: dict[str, Any], prefix: str = "") -> dict[str, Any]: """Flatten nested dicts: {"price": {"amount": 1}} becomes {"price_amount": 1}.""" flat: dict[str, Any] = {} for key, value in record.items(): name = f"{prefix}{key}" if isinstance(value, dict): flat.update(flatten(value, prefix=f"{name}_")) else: flat[name] = value return flat
for key, value in flatten(first).items(): print(f"{key:<15} {value}")id P001name Wireless Earbudscategory Electronicsprice_amount 79.99price_currency USDin_stock Truestock 92rating_average 3.8rating_count 216launch_date 2021-03-01url https://api.example.com/v1/products/P001pandas has the same tool built in. Module 24 teaches pandas; here is a preview. pd.json_normalize() takes a list of nested records and returns a table:
import pandas as pd
pd.set_option("display.width", 100)pd.set_option("display.max_columns", 12)pd.set_option("display.precision", 3)
products = pd.json_normalize(page_1["data"], sep="_")print(products[["id", "category", "price_amount", "rating_average", "stock"]].head(4)) id category price_amount rating_average stock0 P001 Electronics 79.99 3.8 921 P002 Electronics 249.00 3.9 1512 P003 Electronics 1299.00 4.0 163 P004 Electronics 1149.00 4.0 37Lists inside a record, such as the roles of a user, do not flatten into one cell cleanly. Join them into a string ("admin;analyst") or make one row per item, depending on the question.
requests and httpx
Section titled “requests and httpx”Python’s standard library can send HTTP requests (urllib.request), but its API is low level. Two third-party libraries are the usual choice. requests is the classic, used in millions of scripts. httpx has almost the same API and adds async support, HTTP/2 and a built-in test transport. Both are in the course requirements. This code calls the real API; it needs a network, so it does not run on this page:
import httpx
with httpx.Client(base_url="https://api.example.com/v1", timeout=10.0) as client: response = client.get("/products", params={"page": 1, "per_page": 10}) response.raise_for_status() # raise for any status that is not 2xx page = response.json() # parse the JSON body into dicts and lists
print(page["total"], [item["id"] for item in page["data"]][:3])import requests
with requests.Session() as session: response = session.get( "https://api.example.com/v1/products", params={"page": 1, "per_page": 10}, timeout=10, # requests waits forever without this ) response.raise_for_status() page = response.json()
print(page["total"], [item["id"] for item in page["data"]][:3])A client object (httpx.Client or requests.Session) keeps settings that every request shares: a base URL, headers and a timeout. It also keeps a connection pool: open connections that the next request reuses, which saves time on every call after the first. Use it in a with block, so that the connections close at the end. This page keeps a few clients open across examples for the demo and closes them in the last step of Example 7; a script uses with.
| requests | httpx | |
|---|---|---|
| One-off call | requests.get(url, params=...) |
httpx.get(url, params=...) |
| Shared settings | requests.Session() |
httpx.Client(base_url=...) |
| Default timeout | none: waits forever | 5 seconds |
| Redirects | followed by default | not followed; pass follow_redirects=True |
| Async | no | httpx.AsyncClient |
| Fake server for tests | extra package (responses) |
built in: httpx.MockTransport |
| Error for 4xx/5xx | requests.HTTPError |
httpx.HTTPStatusError |
The rest of this module uses httpx. Everything you learn carries over to requests: the method names and arguments are the same.
Run client code offline with MockTransport
Section titled “Run client code offline with MockTransport”A transport is the part of an httpx client that sends bytes over the network. httpx.MockTransport(handler) replaces it with your own function. The handler receives an httpx.Request and returns an httpx.Response. Everything else is the real client code: URL building, query encoding, headers, status checks and JSON decoding. This is the fake from module 11, applied to HTTP.
This handler answers like the shop API, from the saved files:
import httpx
BASE_URL = "https://api.example.com/v1"
def json_file_response( status: int, filename: str, headers: dict[str, str] | None = None) -> httpx.Response: """Build a response whose body is a saved JSON file from data/api/.""" return httpx.Response( status, content=(API_DIR / filename).read_bytes(), headers={"Content-Type": "application/json", **(headers or {})}, )
def shop_api(request: httpx.Request) -> httpx.Response: """Answer like api.example.com/v1, from the saved fixture files.""" path = request.url.path if path == "/v1/products": page = int(request.url.params.get("page", "1")) if 1 <= page <= 3: return json_file_response(200, f"products_page_{page}.json") return httpx.Response(404, json={"error": "not_found", "page": page}) if path == "/v1/forecast": return json_file_response(200, "weather_forecast.json") if path == "/v1/users": return json_file_response(200, "users.json") return httpx.Response(404, json={"error": "not_found", "path": path})
client = httpx.Client( base_url=BASE_URL, transport=httpx.MockTransport(shop_api), timeout=10.0)response = client.get("/products", params={"page": 2, "per_page": 10})print(response.status_code, response.reason_phrase)print(response.url)print(response.headers["content-type"])page_2 = response.json()print(page_2["page"], [item["id"] for item in page_2["data"]])200 OKhttps://api.example.com/v1/products?page=2&per_page=10application/json2 ['P011', 'P012', 'P013', 'P014', 'P015', 'P016', 'P017', 'P018', 'P019', 'P020']A saved response used as test input is an API fixture. Delete the transport= argument and point base_url at a real server, and the same client code talks to the network. httpx.Response(..., json=...) builds a JSON body from a dict, which is handy for small error bodies. client stays open for the rest of this page.
Errors and timeouts
Section titled “Errors and timeouts”Two different things can go wrong with a request:
- The server answers with an error status. You get a response object.
response.raise_for_status()raiseshttpx.HTTPStatusErrorfor any status that is not 2xx: in practice 3xx (httpx does not follow redirects by default), 4xx and 5xx. Without it, your code happily reads an error body as if it were data. - No answer arrives. The host does not exist, the connection is refused or the server is too slow. httpx raises a subclass of
httpx.TransportErrorand there is no response at all.
flowchart TD
E["httpx.HTTPError"] --> S["HTTPStatusError<br/>status not 2xx"]
E --> R["RequestError"]
R --> T["TransportError<br/>no response"]
T --> TO["TimeoutException<br/>ConnectTimeout, ReadTimeout"]
T --> N["NetworkError"]
N --> C["ConnectError"]
The fake API has no page 4:
response = client.get("/products", params={"page": 4})print(response.status_code, response.json())try: response.raise_for_status()except httpx.HTTPStatusError as exc: print(type(exc).__name__, "for status", exc.response.status_code) print(str(exc).splitlines()[0])404 {'error': 'not_found', 'page': 4}HTTPStatusError for status 404Client error '404 Not Found' for url 'https://api.example.com/v1/products?page=4'The body explains the error, so log it before you raise. The exception keeps the response in exc.response and the request in exc.request. Its message has a second line with a link to the documentation of the status code.
A timeout is the longest time the client waits. Without one, a script can hang forever on a server that never answers, and a nightly pipeline never finishes. httpx.Timeout(10.0, connect=3.0) waits at most 3 seconds to connect and 10 seconds for each other step. A handler can raise a timeout to show what your code sees:
def slow_api(request: httpx.Request) -> httpx.Response: raise httpx.ReadTimeout("read timed out after 10.0s", request=request)
with httpx.Client( base_url=BASE_URL, transport=httpx.MockTransport(slow_api), timeout=httpx.Timeout(10.0, connect=3.0),) as slow_client: try: slow_client.get("/forecast") except httpx.TimeoutException as exc: print(type(exc).__name__, "-", exc) print(isinstance(exc, httpx.TransportError))ReadTimeout - read timed out after 10.0sTrueThe fake raises at once, so the page does not wait 10 seconds. Catch httpx.TimeoutException for timeouts only, httpx.TransportError for every “no answer” case and httpx.HTTPError for both status errors and request errors.
Pagination
Section titled “Pagination”A server does not send a million records in one response. It splits the result into pages and the client asks for one page at a time. This is pagination. APIs use one of four styles:
| Style | Request | How you know there is more | Notes |
|---|---|---|---|
| page number | ?page=2&per_page=10 |
page < total_pages |
simple; pages shift if records are added meanwhile |
| offset and limit | ?offset=20&limit=10 |
fewer than limit items came back |
the same idea in rows instead of pages |
| cursor | ?cursor=eyJpZCI6IlAwMjAifQ |
the response has a next_cursor |
stable under inserts; you cannot jump to page 7 |
| next link | follow next in the body or the Link header |
next is not null |
the server builds the URL for you |
The shop API offers page numbers and a next link. Following the link is the most robust choice: your code does not need to know the pagination style at all. Every loop also needs a stop rule that cannot fail, such as a maximum number of pages. A server bug that always returns the same next link would otherwise run your loop forever. Example 3 builds the loop.
Rate limits, retries and backoff
Section titled “Rate limits, retries and backoff”A rate limit caps how many requests a client may send in a time window. It protects the server from overload and from one greedy client. When you go over the limit, the server answers 429 Too Many Requests. The saved body shows what the shop API sends:
rate_limit_body = json.loads((API_DIR / "error_429.json").read_text(encoding="utf-8"))for key, value in rate_limit_body.items(): print(f"{key:<12} {value}")status 429error rate_limit_exceededmessage Too many requests. Limit is 60 requests per minute.retry_after 30limit 60remaining 0reset_at 2024-05-01T12:01:00Zrequest_id req_7f3a9c2e41b8The body says: 60 requests per minute, none left, try again in 30 seconds. The same information travels in the Retry-After response header, as a number of seconds or as an HTTP date. A polite client reads it and waits at least that long.
Some failures are transient errors (module 11): they go away by themselves. Retry those, and only those:
| Failure | Retry? | Wait |
|---|---|---|
429 Too Many Requests |
yes | Retry-After if present, else backoff |
500, 502, 503, 504 |
yes | exponential backoff |
| timeout, connection error | yes | exponential backoff |
400, 401, 403, 404, 422 |
no | fix the request, the key or the URL |
any error on a non-idempotent POST |
only with an idempotency key | the API must support it |
An idempotency key is a unique id that the client sends with a POST, often in an Idempotency-Key header. The server performs the action only once per key, so a retry of the same request cannot create a duplicate.
Exponential backoff (module 11) doubles the wait after each failed attempt, up to a cap. With base wait , cap and attempt :
If a thousand clients fail at the same moment, plain backoff makes them all retry at the same moments too. Jitter spreads them out: each client waits a random time between 0 and (“full jitter”). A seeded random generator keeps the demo reproducible:
import random
def backoff_delay(attempt: int, base: float = 1.0, cap: float = 30.0) -> float: """Exponential backoff: base, 2*base, 4*base, ... capped at cap seconds.""" return min(cap, base * 2 ** (attempt - 1))
rng = random.Random(42)delays = [backoff_delay(k) for k in range(1, 8)]jittered = [round(rng.uniform(0, d), 2) for d in delays]print("backoff:", delays)print("jitter: ", jittered)backoff: [1.0, 2.0, 4.0, 8.0, 16.0, 30.0, 30.0]jitter: [0.64, 0.05, 1.1, 1.79, 11.78, 20.3, 26.77]The waits double from 1 second to the cap of 30 seconds. The jittered waits are random but never longer than the plain ones. A client can also avoid 429s from the start: at 60 requests per minute, wait at least 60 / 60 = 1 second between requests. This is throttling on the client side.
Secrets: API keys in environment variables
Section titled “Secrets: API keys in environment variables”Most APIs want proof of who you are. An API key is a secret string that the API issues to you. A common scheme sends it as a bearer token in the Authorization: Bearer <key> header: whoever holds the token gets access, like a ticket.
A key in your code ends up in git history, in screenshots and in shared notebooks. Anyone who sees it can use your account. So keep the key out of the code. Put it in an environment variable (module 09) and read it with os.environ.get():
export MAPLE_API_KEY="mf_live_7Q2xK9pL4vR8" # this terminal onlypython fetch_products.py$env:MAPLE_API_KEY = "mf_live_7Q2xK9pL4vR8" # this terminal onlypython fetch_products.pyThe script fails early and clearly when the key is missing:
import os
def get_api_key(name: str = "MAPLE_API_KEY") -> str: """Return the API key from the environment, or fail with a clear message.""" key = os.environ.get(name) if not key: raise RuntimeError(f"Set the {name} environment variable first.") return key
get_api_key("MAPLE_API_KEY_MISSING")RuntimeError: Set the MAPLE_API_KEY_MISSING environment variable first.The message names the variable, but it never contains a key. When you must show a key, for example to check which one is loaded, mask it:
os.environ["MAPLE_API_KEY"] = "mf_live_7Q2xK9pL4vR8" # stands in for the export above
def mask_secret(secret: str, visible: int = 4) -> str: """Hide all but the last few characters: mf_live_7Q2x... -> ********4vR8.""" return "*" * 8 + secret[-visible:]
api_key = get_api_key()print("key loaded:", mask_secret(api_key), f"({len(api_key)} characters)")key loaded: ********4vR8 (20 characters)On your machine you can keep keys in a .env file: a text file of NAME=value lines in the project folder. The python-dotenv package loads it into os.environ. It is not in the course requirements; install it with uv pip install python-dotenv if you want it.
from dotenv import load_dotenv
load_dotenv() # reads .env into os.environ; existing variables winapi_key = get_api_key()Parsing HTML with BeautifulSoup
Section titled “Parsing HTML with BeautifulSoup”Some data exists only on web pages made for people. Web scraping means extracting data from such pages with a program. Use it when no API exists, and use it politely:
- Read the site’s terms and its
robots.txt, the file at the site root that says which paths bots may visit. - Send a
User-Agentthat names your program and a contact address. - Go slowly: one request per second or less, and cache what you fetched.
- Prefer an API or a data export when one exists. HTML changes without notice and breaks scrapers.
A web page is written in HTML (HyperText Markup Language). HTML wraps content in tags such as <td> and </td>. A start tag, its content and its end tag form an HTML element. A start tag can carry attributes: name="value" pairs such as class="price" or data-id="P001". Elements nest inside each other, so a page is a tree.
BeautifulSoup (package beautifulsoup4, module bs4) reads HTML into a tree of Python objects that you can search. It needs a parser, the code that reads the text; "html.parser" comes with Python. You find elements with CSS selectors, the same patterns that style sheets use:
| Selector | Matches | In catalog.html |
|---|---|---|
td |
every <td> element |
all table cells |
.price |
elements with class price |
prices in the table and the cards |
#products |
the element with id="products" |
the price table |
tbody tr |
<tr> anywhere inside <tbody> |
the 12 data rows |
h2.product-name > a |
<a> directly inside <h2 class="product-name"> |
product links |
[data-rating] |
elements that have this attribute | the rating stars |
a[rel="next"] |
links with this attribute value | the pagination link |
from bs4 import BeautifulSoup
html = (API_DIR / "catalog.html").read_text(encoding="utf-8")soup = BeautifulSoup(html, "html.parser")print(soup.title.get_text())table = soup.select_one("table#products")rows = table.select("tbody tr")print(len(rows), "rows; first row id:", rows[0]["data-id"])print([td.get_text(strip=True) for td in rows[0].find_all("td")])next_link = soup.find("a", rel="next")print(next_link["href"], next_link["rel"], next_link.get_text(strip=True))Maple & Finch Market | Product catalog12 rows; first row id: P001['P001', 'Wireless Earbuds', 'Electronics', '$79.99', 'In stock']/catalog?page=2 ['next'] Next »The methods you need most:
| Method | Returns | Example |
|---|---|---|
select(css) |
a list of all matches | soup.select("article.product-card") |
select_one(css) |
the first match or None |
card.select_one("span.price") |
find_all(name, attrs) |
a list of all matches | row.find_all("td") |
find(name, attrs) |
the first match or None |
soup.find("a", rel="next") |
tag["attr"] |
an attribute value; KeyError if absent |
row["data-id"] |
tag.get("attr") |
an attribute value or None |
card.get("data-product-id") |
tag.get_text(strip=True) |
the text inside, trimmed | "$79.99" |
BeautifulSoup decodes HTML entities, the escape codes of HTML: & in the title became &. Some attributes, such as class and rel, can hold several values, so BeautifulSoup returns them as lists: ['next'], not 'next'.
Worked examples
Section titled “Worked examples”Example 1 — Turn one page of products into tidy records
Section titled “Example 1 — Turn one page of products into tidy records”Goal: The merchandising team sends you a saved response, data/api/products_page_1.json. Turn its 10 products into flat records and summarize stock and prices by category.
Step 1 — Check the page metadata
Section titled “Step 1 — Check the page metadata”for key, value in page_1.items(): print(f"{key:<12} {value if key != 'data' else f'list of {len(value)} records'}")page 1per_page 10total 30total_pages 3next https://api.example.com/v1/products?page=2&per_page=10data list of 10 recordsLook at the metadata before the records. It tells you that this is page 1 of 3, that the API holds 30 products and where page 2 lives. Your code needs all three facts to collect the full dataset.
Step 2 — Look at the fields of one record
Section titled “Step 2 — Look at the fields of one record”for key, value in page_1["data"][5].items(): print(f"{key:<12} {type(value).__name__:<6} {value}")id str P006name str Espresso Machinecategory str Homeprice dict {'amount': 349.0, 'currency': 'USD'}in_stock bool Falsestock int 0rating dict {'average': 4.0, 'count': 68}launch_date str 2020-04-20url str https://api.example.com/v1/products/P006Record 6 is P006, an out-of-stock product. Two fields are nested dicts. launch_date is a string, because JSON has no date type. url points to the product’s own endpoint.
Step 3 — Flatten the records and keep the useful columns
Section titled “Step 3 — Flatten the records and keep the useful columns”COLUMNS = ["id", "name", "category", "price_amount", "in_stock", "stock", "rating_average", "rating_count"]
records = [ {column: flat[column] for column in COLUMNS} for flat in map(flatten, page_1["data"])]print(len(records), "records,", len(records[0]), "columns")print(list(records[5]))print(list(records[5].values()))10 records, 8 columns['id', 'name', 'category', 'price_amount', 'in_stock', 'stock', 'rating_average', 'rating_count']['P006', 'Espresso Machine', 'Home', 349.0, False, 0, 4.0, 68]Each record is now one flat dict with the same 8 keys. A list of such dicts is the shape that csv.DictWriter, pd.DataFrame and most plotting code accept directly. Choosing the columns here also documents which fields your analysis depends on.
Step 4 — Summarize by category
Section titled “Step 4 — Summarize by category”from collections import defaultdictfrom statistics import mean
by_category: dict[str, list[dict[str, Any]]] = defaultdict(list)for record in records: by_category[record["category"]].append(record)
for category, items in by_category.items(): prices = [item["price_amount"] for item in items] out = [item["id"] for item in items if not item["in_stock"]] print(f"{category:<12} n={len(items)} mean price {mean(prices):8.2f} out: {out}")Electronics n=5 mean price 595.40 out: []Home n=5 mean price 207.59 out: ['P006']Page 1 holds all 5 Electronics products and all 5 Home products. P006, the espresso machine, is out of stock. This summary covers one page only: a report for the whole catalog needs all three pages (Example 3).
Common mistakes:
- Treating one page as the full dataset. Check
totalandtotal_pagesbefore you report numbers. - Reading
record["price"]and getting a dict instead of a number. Flatten first, or readrecord["price"]["amount"]. - Assuming every record has every key. A real API may leave out optional fields; use
record.get("key")for those.
Example 2 — Fetch one page and check it before you use it
Section titled “Example 2 — Fetch one page and check it before you use it”Goal: A nightly job downloads the product list. Make the client identify itself, check the status and the content type, and stop with a clear error when the API sends something unexpected.
Step 1 — Configure the client once
Section titled “Step 1 — Configure the client once”HEADERS = { "Accept": "application/json", "User-Agent": "maple-analytics/1.0 (data-team@example.org)",}api = httpx.Client( base_url=BASE_URL, headers=HEADERS, timeout=httpx.Timeout(10.0, connect=3.0), transport=httpx.MockTransport(shop_api),)response = api.get("/products", params={"page": 1, "per_page": 10})print(response.request.method, response.request.url)print(response.request.headers["user-agent"])print(response.status_code, response.headers["content-type"])GET https://api.example.com/v1/products?page=1&per_page=10maple-analytics/1.0 (data-team@example.org)200 application/jsonThe headers, the timeout and the base URL now apply to every request of this client. response.request is the request that httpx really sent, which is the first thing to inspect when an API rejects you. A clear User-Agent tells the API owner who to contact when your job causes trouble.
Step 2 — Write a check for the response
Section titled “Step 2 — Write a check for the response”REQUIRED_KEYS = {"page", "total", "total_pages", "next", "data"}
def parse_page(response: httpx.Response) -> dict[str, Any]: """Return the JSON page, or raise if the response is not a valid page.""" response.raise_for_status() content_type = response.headers.get("content-type", "") if not content_type.startswith("application/json"): raise ValueError(f"expected JSON, got {content_type!r}") page = response.json() missing = REQUIRED_KEYS - page.keys() if missing: raise ValueError(f"page is missing keys: {sorted(missing)}") return page
page = parse_page(response)print(page["page"], page["total"], len(page["data"]))1 30 10The function checks three things in order: the status, the format and the shape. Each check gives a precise message. Checking the shape at the door means that the rest of the pipeline can trust the data.
Step 3 — Meet a maintenance page
Section titled “Step 3 — Meet a maintenance page”def maintenance_api(request: httpx.Request) -> httpx.Response: html_page = "<html><body><h1>Down for maintenance</h1></body></html>" return httpx.Response(200, text=html_page, headers={"Content-Type": "text/html"})
with httpx.Client( base_url=BASE_URL, transport=httpx.MockTransport(maintenance_api)) as broken: reply = broken.get("/products") print(reply.status_code, reply.headers["content-type"]) parse_page(reply)200 text/htmlValueError: expected JSON, got 'text/html'Some proxies and load balancers answer with an HTML page and status 200 during maintenance. Calling reply.json() on it would raise a confusing JSONDecodeError. The content-type check turns it into a clear message.
Common mistakes:
- Building the URL by hand:
f"{BASE_URL}/products?page={page}". It breaks on spaces and special characters. Passparams=. - Calling
response.json()beforeraise_for_status(). You parse an error body and fail later with aKeyError. - Creating a new client for every request inside a loop. Each one opens new connections. Create one client and reuse it.
Example 3 — Collect every page of a paginated API
Section titled “Example 3 — Collect every page of a paginated API”Goal: Download all 30 products by following the next links, check that nothing is missing, summarize the catalog and save it as output/products.csv for the analytics team.
Step 1 — Write a generator that follows the next link
Section titled “Step 1 — Write a generator that follows the next link”from collections.abc import Iterator
def iter_pages( client: httpx.Client, path: str, *, per_page: int = 10, max_pages: int = 100) -> Iterator[dict[str, Any]]: """Yield each page of a paginated endpoint by following its next links.""" url: str | None = path params: dict[str, Any] | None = {"page": 1, "per_page": per_page} for _ in range(max_pages): if url is None: return page = parse_page(client.get(url, params=params)) print(f"page {page['page']}/{page['total_pages']}: {len(page['data'])} items") yield page url, params = page["next"], None # the next link already has its query raise RuntimeError(f"stopped after {max_pages} pages; is next always set?")
pages = list(iter_pages(api, "/products"))print(len(pages), "pages")page 1/3: 10 itemspage 2/3: 10 itemspage 3/3: 10 items3 pagesThe generator (module 10) yields one page at a time, so a caller can stop early or process pages as they arrive. The next link is a full URL with its own query, so the loop sends params=None after page 1. httpx replaces the whole query string of a URL when you pass params, so any other value would break the link. The for _ in range(max_pages) loop is the safety stop.
Step 2 — Check that the download is complete
Section titled “Step 2 — Check that the download is complete”items = [item for page in pages for item in page["data"]]ids = [item["id"] for item in items]print(len(items), "items; expected", pages[0]["total"])print("unique ids:", len(set(ids)), "| first:", ids[0], "| last:", ids[-1])assert len(items) == pages[0]["total"] == len(set(ids))30 items; expected 30unique ids: 30 | first: P001 | last: P030Two checks catch the classic pagination bugs: a missing page gives fewer items than total, and a page fetched twice gives duplicate ids. An assert (module 06) stops the job before it writes a wrong file.
Step 3 — Build tidy records and a catalog summary
Section titled “Step 3 — Build tidy records and a catalog summary”catalog = [{column: flatten(item)[column] for column in COLUMNS} for item in items]
summary: dict[str, dict[str, Any]] = {}for record in catalog: row = summary.setdefault(record["category"], {"n": 0, "stock": 0, "prices": []}) row["n"] += 1 row["stock"] += record["stock"] row["prices"].append(record["price_amount"])
print(f"{'category':<12}{'products':>9}{'units':>7}{'mean price':>12}")for category, row in sorted(summary.items()): print(f"{category:<12}{row['n']:>9}{row['stock']:>7}{mean(row['prices']):>12.2f}")out_of_stock = [r["id"] for r in catalog if not r["in_stock"]]print("out of stock:", out_of_stock)category products units mean priceBeauty 5 553 30.89Books 5 683 24.29Clothing 5 649 60.69Electronics 5 381 595.40Home 5 471 207.59Sports 5 428 146.79out of stock: ['P006', 'P019']Six categories with 5 products each make the 30 products. Electronics has the highest mean price because of the TV and the laptop. Two products are out of stock: P006 and P019.
Step 4 — Save the records as CSV
Section titled “Step 4 — Save the records as CSV”import csv
output_dir = Path("output")output_dir.mkdir(exist_ok=True)csv_path = output_dir / "products.csv"with csv_path.open("w", newline="", encoding="utf-8") as f: writer = csv.DictWriter(f, fieldnames=COLUMNS) writer.writeheader() writer.writerows(catalog)
lines = csv_path.read_text(encoding="utf-8").splitlines()print(len(lines), "lines")print("\n".join(lines[:3]))31 linesid,name,category,price_amount,in_stock,stock,rating_average,rating_countP001,Wireless Earbuds,Electronics,79.99,True,92,3.8,216P002,Noise-Cancelling Headphones,Electronics,249.0,True,151,3.9,141The file has one header line and 30 data lines. newline="" stops the csv module from writing blank lines on Windows (module 07). pd.read_csv("output/products.csv") now loads the catalog in one line.
Common mistakes:
- Sending
params={"page": 1}together with thenextURL. httpx replaces the link’s whole query string with yourparams, so the loop fetches page 1 again and again. Evenparams={}drops the query. (requests appends instead, which gives?page=2&per_page=10&page=1.) - Stopping when a page is shorter than
per_pageon an API that does not promise full pages. Use the API’s own signal:next,total_pagesor a cursor. - Collecting pages without a safety stop. A server bug becomes an infinite loop and a huge bill.
Example 4 — Retry rate limits and server errors
Section titled “Example 4 — Retry rate limits and server errors”Goal: The shop API rate-limits the nightly download and sometimes fails with 503 Service Unavailable. Retry these failures with backoff and Retry-After, give up after a few attempts, and test it all without waiting.
Step 1 — Script a flaky server
Section titled “Step 1 — Script a flaky server”from collections.abc import Callable
Handler = Callable[[httpx.Request], httpx.Response]
def rate_limit_response() -> httpx.Response: """The saved 429 body, with the headers a real API sends with it.""" headers = {"Retry-After": "30", "X-RateLimit-Limit": "60", "X-RateLimit-Remaining": "0"} return json_file_response(429, "error_429.json", headers)
def flaky(handler: Handler, failures: list[int]) -> Handler: """Answer the first requests with the given statuses, then delegate.""" queue = list(failures)
def handle(request: httpx.Request) -> httpx.Response: if queue: status = queue.pop(0) response = (rate_limit_response() if status == 429 else httpx.Response(status, json={"error": "unavailable"})) else: response = handler(request) query = f"?{request.url.params}" if request.url.params else "" print(f" server: {request.url.path}{query} -> {response.status_code}") return response
return handle
flaky_client = httpx.Client( base_url=BASE_URL, transport=httpx.MockTransport(flaky(shop_api, [429, 503])))first_try = flaky_client.get("/products", params={"page": 2})print(first_try.status_code, first_try.headers["retry-after"])print(first_try.json()["error"]) server: /v1/products?page=2 -> 429429 30rate_limit_exceededThe fake server fails twice, with a 429 and then a 503, and answers normally after that. It prints each request, so you can see every attempt. The 429 response carries the Retry-After: 30 header and the saved error body.
Step 2 — Write a status-aware retry function
Section titled “Step 2 — Write a status-aware retry function”import time
RETRY_STATUSES = frozenset({429, 500, 502, 503, 504})
def retry_after_seconds(response: httpx.Response) -> float | None: """Seconds from a numeric Retry-After header, or None if it is absent.""" value = response.headers.get("Retry-After") return float(value) if value is not None and value.isdigit() else None
def get_with_retry( client: httpx.Client, url: str, *, params: dict[str, Any] | None = None, max_attempts: int = 4, base_delay: float = 1.0, max_wait: float = 60.0, rng: random.Random | None = None, sleep: Callable[[float], None] = time.sleep,) -> httpx.Response: """GET url; retry timeouts, connection errors, 429 and 5xx with backoff.""" for attempt in range(1, max_attempts): backoff = backoff_delay(attempt, base_delay) if rng is not None: backoff = rng.uniform(0, backoff) # full jitter try: response = client.get(url, params=params) except httpx.TransportError as exc: reason, wait = type(exc).__name__, backoff else: if response.status_code not in RETRY_STATUSES: response.raise_for_status() # other 4xx: retrying will not help return response reason = str(response.status_code) wait = retry_after_seconds(response) or backoff if wait > max_wait: # the server asks for more than this job allows response.raise_for_status() print(f"attempt {attempt} failed ({reason}); waiting {wait:g}s") sleep(wait) response = client.get(url, params=params) # last attempt: errors propagate response.raise_for_status() return responseThe loop makes up to max_attempts - 1 attempts that may fail and retry. A success, or an error that retrying cannot fix, leaves at once. A response with a Retry-After header, usually a 429, waits as long as the header says; other failures use exponential backoff. If the server asks for longer than max_wait, the function gives up at once with the server’s error instead of blocking the job for an hour. Pass rng=random.Random() to add full jitter to the backoff waits; the examples leave it out so that the waits are easy to read. The final attempt runs outside the loop, so its error reaches the caller. sleep is injected, as in module 11.
Step 3 — Run it with a recording sleep
Section titled “Step 3 — Run it with a recording sleep”waits: list[float] = []page_2 = get_with_retry( flaky_client, "/products", params={"page": 2}, sleep=waits.append)print(page_2.status_code, page_2.json()["data"][0]["id"])print("waits:", waits, "-> would have waited", sum(waits), "seconds") server: /v1/products?page=2 -> 503attempt 1 failed (503); waiting 1s server: /v1/products?page=2 -> 200200 P011waits: [1.0] -> would have waited 1.0 secondswaits.append has the right shape for a sleep function: it takes a number and returns None. The flaky client had already used its 429 in Step 1, so this call starts with the 503, waits 1 second of backoff and succeeds on attempt 2. The test took no real time.
Step 4 — Honor Retry-After and survive a timeout
Section titled “Step 4 — Honor Retry-After and survive a timeout”calls = 0
def timeout_then_429(request: httpx.Request) -> httpx.Response: global calls calls += 1 if calls == 1: raise httpx.ConnectTimeout("connect timed out", request=request) if calls == 2: return rate_limit_response() return shop_api(request)
waits = []transport = httpx.MockTransport(timeout_then_429)with httpx.Client(base_url=BASE_URL, transport=transport) as retry_client: result = get_with_retry( retry_client, "/products", params={"page": 3}, sleep=waits.append )print(result.status_code, "after", calls, "calls; waits:", waits)attempt 1 failed (ConnectTimeout); waiting 1sattempt 2 failed (429); waiting 30s200 after 3 calls; waits: [1.0, 30.0]The timeout raised an exception, so there was no response: the function caught httpx.TransportError and waited 1 second of backoff. The 429 then asked for 30 seconds, and the function waited exactly that long instead of its own 2 seconds. Asking again earlier would only earn another 429.
Step 5 — Give up when the server stays down
Section titled “Step 5 — Give up when the server stays down”waits = []always_down = httpx.Client( base_url=BASE_URL, transport=httpx.MockTransport(lambda request: httpx.Response(503)),)try: get_with_retry(always_down, "/forecast", sleep=waits.append)except httpx.HTTPStatusError as exc: print("gave up:", str(exc).splitlines()[0])print("waits:", waits)attempt 1 failed (503); waiting 1sattempt 2 failed (503); waiting 2sattempt 3 failed (503); waiting 4sgave up: Server error '503 Service Unavailable' for url 'https://api.example.com/v1/forecast'waits: [1.0, 2.0, 4.0]Four attempts, three waits of 1, 2 and 4 seconds, then the last 503 reaches the caller as an HTTPStatusError. Here the except prints it; in a nightly job you let it propagate, so the job fails loudly and the scheduler alerts someone. Retrying forever would hide the outage.
Common mistakes:
- Retrying every status, including 400, 401 and 404. These fail the same way every time; you only add load and delay the error message.
- Ignoring
Retry-After. Retrying a 429 sooner than the server asks earns another 429, and some APIs block clients that keep doing it. - Retrying a
POSTthat creates an order. If the first request worked but its response got lost, the retry creates a second order. Retry only idempotent requests, or use the API’s idempotency key. - Calling
time.sleep()in tests. Inject the sleep function.
Example 5 — Turn an hourly forecast into daily features
Section titled “Example 5 — Turn an hourly forecast into daily features”Goal: A demand-forecasting model for the Chicago store uses weather as input. Fetch the 48-hour forecast, flatten the hourly records, build one feature row per day and check it against the API’s own daily summary.
Step 1 — Fetch the forecast and look at its shape
Section titled “Step 1 — Fetch the forecast and look at its shape”forecast = api.get("/forecast").raise_for_status().json()print(forecast["location"]["name"], forecast["location"]["timezone"])print(list(forecast))print(forecast["units"])print(len(forecast["hourly"]), "hourly records, from", forecast["hourly"][0]["time"])Chicago America/Chicago['location', 'generated_at', 'units', 'current', 'daily', 'hourly']{'temperature': '°C', 'precipitation': 'mm', 'wind_speed': 'km/h'}48 hourly records, from 2024-05-01T00:00raise_for_status() returns the response itself when the status is fine, so the three calls chain on one line. The units block matters: a model trained on °C breaks quietly if a later download arrives in °F.
Step 2 — Flatten the hourly records
Section titled “Step 2 — Flatten the hourly records”from datetime import datetime
hourly = []for hour in forecast["hourly"]: flat = flatten(hour) flat["time"] = datetime.fromisoformat(flat["time"]) hourly.append(flat)
print("new keys:", [key for key in hourly[0] if key not in forecast["hourly"][0]])print(hourly[24]["time"], hourly[24]["temperature_c"], hourly[24]["condition_text"])new keys: ['wind_speed_kmh', 'wind_direction_deg', 'condition_code', 'condition_text']2024-05-02 00:00:00 10.6 Moderate rainflatten() turns wind.speed_kmh into wind_speed_kmh and condition.text into condition_text. Converting time to a datetime once, at the door, makes every later step simpler: you can read .date() and .hour instead of slicing strings.
Step 3 — Aggregate one feature row per day
Section titled “Step 3 — Aggregate one feature row per day”days: dict[str, list[dict[str, Any]]] = defaultdict(list)for record in hourly: days[record["time"].date().isoformat()].append(record)
features = []for day, records_of_day in days.items(): temps = [r["temperature_c"] for r in records_of_day] rain = [r for r in records_of_day if r["precipitation_mm"] > 0] features.append({ "date": day, "min_c": min(temps), "max_c": max(temps), "rain_mm": round(sum(r["precipitation_mm"] for r in records_of_day), 1), "rain_hours": len(rain), "max_wind_kmh": max(r["wind_speed_kmh"] for r in records_of_day), })print(f"{'date':<11}{'min_c':>6}{'max_c':>6}{'rain_mm':>8}{'rain_hours':>11}" f"{'max_wind':>9}")for row in features: print(f"{row['date']:<11}{row['min_c']:>6}{row['max_c']:>6}{row['rain_mm']:>8}" f"{row['rain_hours']:>11}{row['max_wind_kmh']:>9}")date min_c max_c rain_mm rain_hours max_wind2024-05-01 7.2 20.4 0.0 0 27.32024-05-02 7.7 20.1 12.1 10 27.1Each day became one row with five numeric features. May 2 has 10 hours of rain and 12.1 mm in total. Rounding rain_mm removes float noise from the sum, as in module 01.
Step 4 — Check the features against the API’s daily block
Section titled “Step 4 — Check the features against the API’s daily block”for row, daily in zip(features, forecast["daily"], strict=True): same = (row["date"], row["min_c"], row["max_c"]) == ( daily["date"], daily["min_c"], daily["max_c"]) print(row["date"], "matches daily summary:", same)
rain_times = [r["time"] for r in hourly if r["precipitation_mm"] > 0]print("rain from", rain_times[0].strftime("%m-%d %H:%M"), "to", rain_times[-1].strftime("%m-%d %H:%M"))2024-05-01 matches daily summary: True2024-05-02 matches daily summary: Truerain from 05-02 00:00 to 05-02 09:00Your daily minimum and maximum equal the API’s own summary, so the aggregation is correct. The rainy window runs from midnight to 09:00 on May 2. Cross-checking against a second source in the same response costs two lines and catches unit and grouping bugs.
Common mistakes:
- Grouping by the date of a time in the wrong zone. Here the times are already local to Chicago. When an API sends UTC times or offsets,
datetime.fromisoformat()alone keeps the sender’s date. Convert to the store’s zone before you group:when.astimezone(ZoneInfo(forecast["location"]["timezone"])).date()(module 09). - Mixing units. Check the
unitsblock, and convert at the door. - Treating
precipitation_probabilityas an amount of rain. It is a percentage chance;precipitation_mmis the amount.
Example 6 — Call an authenticated API with a key from the environment
Section titled “Example 6 — Call an authenticated API with a key from the environment”Goal: The /v1/users endpoint lists the analysts who use the shop’s reporting tool, and it needs an API key. Send the key from the environment, see what happens without it, and summarize the active users by city without printing the secret.
Step 1 — A fake server that checks the key
Section titled “Step 1 — A fake server that checks the key”VALID_KEYS = {"mf_live_7Q2xK9pL4vR8"} # the server's list of issued keys
def secure_api(request: httpx.Request) -> httpx.Response: """Like shop_api, but /v1/users needs a valid bearer token.""" if request.url.path == "/v1/users": token = request.headers.get("Authorization", "").removeprefix("Bearer ") if token not in VALID_KEYS: body = {"error": "unauthorized", "message": "Missing or invalid API key."} headers = {"WWW-Authenticate": "Bearer"} return httpx.Response(401, json=body, headers=headers) return shop_api(request)
anonymous = httpx.Client(base_url=BASE_URL, transport=httpx.MockTransport(secure_api))denied = anonymous.get("/users")print(denied.status_code, denied.reason_phrase, denied.json()["message"])401 Unauthorized Missing or invalid API key.Without the header, the server answers 401 Unauthorized and a JSON message. 401 is not a transient error: retrying without a key fails the same way. The WWW-Authenticate header tells the client which scheme the server expects.
Step 2 — Send the key from the environment
Section titled “Step 2 — Send the key from the environment”authed = httpx.Client( base_url=BASE_URL, headers={"Authorization": f"Bearer {get_api_key()}"}, transport=httpx.MockTransport(secure_api),)users_response = authed.get("/users")print(users_response.status_code, "-", len(users_response.json()), "users")shown = repr(authed.headers)print("[secure]" in shown, api_key in shown)200 - 10 usersTrue Falseget_api_key() reads the variable that the terminal (here, the earlier os.environ line) set. The client sends the header on every request. When httpx prints headers, it shows 'authorization': '[secure]' instead of the key, so the printed text does not contain the key. Your own log lines get no such protection, so never write print(api_key) or put the key in an exception message.
Step 3 — Summarize the users
Section titled “Step 3 — Summarize the users”from collections import Counter
users = users_response.json()active = [u for u in users if u["active"]]by_city = Counter(u["address"]["city"] for u in active)admins = [u["username"] for u in users if "admin" in u["roles"]]print(len(active), "active of", len(users))print(by_city.most_common(3))print("admins:", admins)9 active of 10[('Philadelphia', 2), ('New York', 2), ('Denver', 1)]admins: ['yukit']users.json is a bare list, not a wrapper with data, so you loop over the response directly. Read the shape of every endpoint; one API can mix both styles.
Step 4 — Keep the key on its own host
Section titled “Step 4 — Keep the key on its own host”seen: list[str] = []
def recording_server(request: httpx.Request) -> httpx.Response: """Record which host received an Authorization header.""" has_key = "authorization" in request.headers seen.append(f"{request.url.host}: {'key sent' if has_key else 'no key'}") return httpx.Response(200, text="ok")
key_header = {"Authorization": f"Bearer {get_api_key()}"}recorder = httpx.MockTransport(recording_server)with httpx.Client(base_url=BASE_URL, headers=key_header, transport=recorder) as shared: shared.get("/users") shared.get("https://shop.example.com/catalog") # another host, same clientprint("one shared client: ", seen)
seen.clear()api_only = httpx.Client(base_url=BASE_URL, headers=key_header, transport=recorder)web = httpx.Client(base_url="https://shop.example.com", transport=recorder)with api_only, web: api_only.get("/users") web.get("/catalog")print("one client per host:", seen)one shared client: ['api.example.com: key sent', 'shop.example.com: key sent']one client per host: ['api.example.com: key sent', 'shop.example.com: no key']A fake server that records the request headers shows the risk. httpx sends a client’s default headers with every request, also to a full URL on another host. The shared client handed the bearer token to the web shop, and to every proxy and log on the way there. The fix is one client per base URL, with the key only on the API client.
Common mistakes:
- Writing the key into the script “just for now”. It reaches git in the next commit. Read it from the environment from the first line you write.
- Printing a key to debug it. Print its length and its last characters with a mask.
- Retrying a 401 or 403. Check that the variable is set and that the key has the right permissions.
- Reusing the authenticated client for another host. Its
Authorizationheader goes along. Give each host its own client.
Example 7 — Scrape the catalog page into a CSV
Section titled “Example 7 — Scrape the catalog page into a CSV”Goal: The shop’s public catalog page, data/api/catalog.html, shows old prices that the API does not have. Scrape the price table and the product cards, compute the discounts, save a CSV and check the scraped prices against the API.
Step 1 — Turn the table rows into records
Section titled “Step 1 — Turn the table rows into records”def parse_price(text: str) -> float: """'$1,299.00' -> 1299.0""" return float(text.strip().removeprefix("$").replace(",", ""))
headers = [th.get_text(strip=True).lower() for th in table.select("thead th")]table_rows = []for tr in table.select("tbody tr"): cells = dict(zip(headers, (td.get_text(strip=True) for td in tr.find_all("td")), strict=True)) cells["price"] = parse_price(cells["price"]) cells["in_stock"] = cells.pop("stock") == "In stock" table_rows.append(cells)
print(headers)print(list(table_rows[2]))print(list(table_rows[2].values()))print(table_rows[7]["product"])['id', 'product', 'category', 'price', 'stock']['id', 'product', 'category', 'price', 'in_stock']['P003', '55-inch 4K Smart TV', 'Electronics', 1299.0, True]Chef's Knife SetThe header row gives the keys, so the code does not depend on the column order. Prices arrive as display text, so parse_price() removes the currency sign and the thousands separator. The entity ' in “Chef’s Knife Set” came out as a normal apostrophe.
Step 2 — Read the product cards and their attributes
Section titled “Step 2 — Read the product cards and their attributes”cards = []for card in soup.select("article.product-card"): old = card.select_one("span.price-old") reviews_text = card.select_one("span.reviews").get_text(strip=True) # (216 reviews) cards.append({ "id": card["data-product-id"], "link": card.select_one("h2.product-name > a")["href"], "price": parse_price(card.select_one("span.price").get_text()), "old_price": parse_price(old.get_text()) if old else None, "rating": float(card.select_one("span.rating")["data-rating"]), "reviews": int(reviews_text.strip("()").split()[0]), })
print(len(cards), "cards")for key, value in cards[1].items(): print(f"{key:<10} {value}")12 cardsid P002link /products/p002-noise-cancelling-headphonesprice 249.0old_price 311.25rating 3.9reviews 141The useful data sits in attributes as much as in text: data-product-id, href and data-rating are cleaner than the visible text, which shows stars. select_one() returns None when a card has no old price, so the code tests it before it reads the text.
Step 3 — Compute the discounts
Section titled “Step 3 — Compute the discounts”for c in cards: if c["old_price"] is not None: discount = 1 - c["price"] / c["old_price"] print(f"{c['id']} {c['old_price']:>7.2f} -> {c['price']:>7.2f}" f" ({discount:.0%} off)")P002 311.25 -> 249.00 (20% off)P006 436.25 -> 349.00 (20% off)P010 87.49 -> 69.99 (20% off)Three products are on sale, each at 20% off. The format spec :.0% multiplies by 100 and adds the percent sign (module 02).
Step 4 — Save the scraped table as CSV
Section titled “Step 4 — Save the scraped table as CSV”scraped_path = output_dir / "catalog_prices.csv"with scraped_path.open("w", newline="", encoding="utf-8") as f: writer = csv.DictWriter(f, fieldnames=list(table_rows[0])) writer.writeheader() writer.writerows(table_rows)print("\n".join(scraped_path.read_text(encoding="utf-8").splitlines()[:3]))id,product,category,price,in_stockP001,Wireless Earbuds,Electronics,79.99,TrueP002,Noise-Cancelling Headphones,Electronics,249.0,TrueThe scraped data now has the same tidy shape as the API data. The CSV writes True and False as text; pd.read_csv() turns them back into booleans.
Step 5 — Cross-check the page against the API
Section titled “Step 5 — Cross-check the page against the API”api_by_id = {record["id"]: record for record in catalog}mismatches = [ (row["id"], row["price"], api_by_id[row["id"]]["price_amount"]) for row in table_rows if row["price"] != api_by_id[row["id"]]["price_amount"] or row["in_stock"] != api_by_id[row["id"]]["in_stock"]]print(len(table_rows), "rows checked;", len(mismatches), "mismatches")12 rows checked; 0 mismatchesThe 12 scraped rows agree with the 30 API records on price and stock. Comparing two sources this way is a standard data check: when it fails one day, the page or the API changed, and you find out before the report goes out.
Step 6 — Close the clients
Section titled “Step 6 — Close the clients”open_clients = [client, api, flaky_client, anonymous, authed]for open_client in open_clients: open_client.close()print(all(c.is_closed for c in open_clients))TrueThis page kept these clients open across examples. A script opens each one in a with block, which closes it at the end.
Common mistakes:
- Selecting by position, such as “the fourth
<td>”. A new column breaks it silently. Use the header names, classes or attributes. - Calling
.get_text()on the result ofselect_one()without checking forNone. A card without the element raisesAttributeError: 'NoneType' object has no attribute 'get_text'. - Comparing
tag["class"] == "price".classis a list in BeautifulSoup. Use"price" in tag["class"], or select with.price. - Scraping a live site in a tight loop. Save the page once, develop against the file, and fetch politely in production.
Pitfalls
Section titled “Pitfalls”| Mistake | Symptom | Fix |
|---|---|---|
| No timeout with requests | The script hangs forever on a dead server | Always pass timeout=; httpx defaults to 5 seconds |
| Reading the body without checking the status | KeyError: 'data' on an error body |
Call response.raise_for_status() first |
response.json without parentheses |
TypeError: 'method' object is not subscriptable |
Call it: response.json() |
| Building query strings with f-strings | Broken URLs for spaces, & or accents |
Pass params={...} |
| Retrying 4xx errors | The same error, only later | Retry only 429, 5xx and transport errors |
Ignoring Retry-After |
More 429s, maybe a block | Wait at least the time the server asks for |
params= plus a next URL in httpx |
The same page again and again | httpx replaces the URL’s query; send params only on the first request |
| A pagination loop with no limit | An endless loop when next never becomes null |
Add max_pages and raise when it is reached |
| An API key in the code | The key leaks through git or a screenshot | Read it with os.environ.get(); mask it in logs |
| One authenticated client for two hosts | The other host receives your key | One client per base URL; the key only on the API client |
.env committed to git |
Everybody can read the secrets | Add .env to .gitignore; revoke a leaked key |
time.sleep() in tests |
Slow tests | Inject sleep and record the waits |
tag["class"] == "price" |
Always False |
class is a list: "price" in tag["class"] |
select_one(...).get_text() on a missing element |
AttributeError: 'NoneType' object has no attribute 'get_text' |
Check for None first |
float("$1,299.00") |
ValueError: could not convert string to float |
Strip $ and , first |
| Expecting httpx to follow redirects | HTTPStatusError for 301 or 302 |
Pass follow_redirects=True |
Where this is used beyond data science
Section titled “Where this is used beyond data science”- Web development: backends call payment, email and map APIs with the same client code, timeouts and retries. Frontend developers read the same status codes in the browser’s network tab.
- Automation: scripts post messages to chat webhooks, open tickets in issue trackers and sync calendars, each through a JSON API with a key from the environment.
- Testing:
httpx.MockTransportand saved fixtures let a test suite check API code without a network, which keeps continuous integration fast and stable. - Operations: health checks poll
/healthendpoints, and monitoring tools page someone when a service answers 5xx for too long.
Summary
Section titled “Summary”- An API answers HTTP requests. A request has a method, a URL with query parameters, headers and an optional body. A response has a status code, headers and a body, usually JSON.
- Status classes decide what you do: 2xx read, 4xx fix the request, 5xx and 429 retry later.
- Use
httpx.Client(orrequests.Session) with a base URL, shared headers and a timeout. Callraise_for_status()before you read the body. httpx.MockTransportreplaces the network with a function, so real client code runs offline against saved fixtures.- Follow
nextlinks or a cursor to collect every page, with a safety limit. Check the count and the uniqueness of ids. - Retry only transient failures, with exponential backoff and optional jitter, and wait as long as
Retry-Aftersays, up to a limit your job can afford. Injectsleepto test without waiting. - Keep API keys in environment variables or a git-ignored
.envfile. Never print or commit them. - BeautifulSoup turns HTML into a searchable tree. Use CSS selectors and attributes, not positions, and scrape politely.
- Flatten nested JSON into tidy records: one row per observation, one column per variable. Then save CSV or load pandas.
Self-check questions
Section titled “Self-check questions”Q1. What are the parts of https://api.example.com/v1/products?page=2&per_page=10?
Answer
The scheme is https, the host is api.example.com, the path (the endpoint) is /v1/products and the query string is page=2&per_page=10, with two query parameters.
Q2. Why is GET safe to retry but POST is not?
Answer
GET only reads, so repeating it has the same effect as sending it once: it is idempotent. POST usually creates something. If the first POST worked and only its response got lost, a retry creates a duplicate, for example a second order.
Q3. A request returns 404. Another returns 503. What should your code do in each case?
Answer
404 Not Found is a client error: the URL or the id is wrong, so retrying will not help. Raise or skip the record, and log it. 503 Service Unavailable is a server error, often transient: retry with exponential backoff and a limit.
Q4. What does httpx.MockTransport replace, and what does it keep?
Answer
It replaces the network transport, the part that sends bytes to a server, with your handler function. It keeps all the client code: base URL, query encoding, headers, timeout settings, status handling and response.json(). So the code you test is the code you ship.
Q5. A pagination loop sends client.get(page["next"], params={"page": 1}). What goes wrong?
Answer
httpx replaces the whole query string of the URL with params, so the request goes to ?page=1 and drops page=2&per_page=10. The loop fetches page 1 again and again until its safety limit stops it. Send params only on the first request, and params=None after that.
Q6. The server answers 429 with Retry-After: 30. Your backoff says 2 seconds. How long do you wait, and why?
Answer
30 seconds. The server says when it will accept requests again. Retrying after 2 seconds earns another 429, and some APIs block clients that ignore the header.
Q7. Why add jitter to exponential backoff?
Answer
Without jitter, many clients that failed at the same moment retry at the same moments too, and they overload the server again. A random wait between 0 and the backoff delay spreads the retries out.
Q8. Name two ways that an API key in a script can leak, and the fix.
Answer
It leaks through git history (even after you delete the line), through screenshots, shared notebooks or log lines that print it. The fix: read it from an environment variable or a git-ignored .env file, mask it in any output, and revoke it at once if it leaks.
Q9. Why does next_link["rel"] return ['next'] and not 'next'?
Answer
In HTML, some attributes, such as rel and class, can hold several space-separated values. BeautifulSoup returns these multi-valued attributes as lists. Test with "next" in tag["rel"].
Q10. When should you scrape a page instead of calling an API?
Answer
Only when no API or data export offers the data, and the site’s terms and robots.txt allow it. An API gives structured, documented data. HTML is made for people and changes without notice, so a scraper breaks more often.
Q11. What does “tidy” mean for a list of product records, and how do you get there from nested JSON?
Answer
One row per product, one column per variable and one value per cell. Flatten the nested objects into columns such as price_amount with a function like flatten() or with pd.json_normalize(records, sep="_").
Track your progress
Section titled “Track your progress”Next steps
Section titled “Next steps”- Exercises: 26 exercises on URLs, status codes, httpx, pagination, retries, secrets and scraping.
- Mini-project: build a resilient catalog snapshot from a rate-limited API and the shop’s web page.
- Cheat sheet: HTTP, httpx, requests, retries, secrets and BeautifulSoup on one page.
- Next module: 17. Algorithms and data structures frames searching, sorting, heaps and sliding windows as data problems.