Skip to content

16. APIs and web data — Exercises

These exercises practice every idea of the APIs and web data lesson. They use the saved API responses in data/api/: three pages of products, a weather forecast, a list of users, a rate-limit error and the shop’s catalog page.

How to work:

  1. Read the task and the expected output.
  2. Copy the setup block and the starter code into a script, and replace each to-do comment with your code.
  3. Run the script from your project folder. Compare your output with the expected output.
  4. Stuck? Open one hint at a time. Open the solution only after a real attempt.

Each solution ends with assert checks. Add the same checks to your own code.

Every exercise starts from this block. The solutions assume it.

import csv
import json
import os
import random
import time
from collections import Counter, defaultdict
from collections.abc import Callable, Iterator
from pathlib import Path
from statistics import mean
from typing import Any
from urllib.parse import parse_qs, urlsplit
import httpx
from bs4 import BeautifulSoup
API_DIR = Path("data/api")
BASE_URL = "https://api.example.com/v1"
Handler = Callable[[httpx.Request], httpx.Response]
def load_json(filename: str) -> Any:
"""Read one saved API response from data/api/."""
return json.loads((API_DIR / filename).read_text(encoding="utf-8"))
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."""
return httpx.Response(
status,
content=(API_DIR / filename).read_bytes(),
headers={"Content-Type": "application/json", **(headers or {})},
)
def find_product(product_id: str) -> dict[str, Any] | None:
for number in (1, 2, 3):
for item in load_json(f"products_page_{number}.json")["data"]:
if item["id"] == product_id:
return item
return None
def shop_api(request: httpx.Request) -> httpx.Response:
"""A fake api.example.com/v1 that answers 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.startswith("/v1/products/"):
item = find_product(path.rsplit("/", 1)[-1])
if item is None:
return httpx.Response(404, json={"error": "not_found"})
return httpx.Response(200, json=item)
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})
def make_client(handler: Handler = shop_api, **kwargs: Any) -> httpx.Client:
"""A real httpx.Client whose transport is the fake server."""
return httpx.Client(
base_url=BASE_URL, transport=httpx.MockTransport(handler), **kwargs
)
def catalog_soup() -> BeautifulSoup:
html = (API_DIR / "catalog.html").read_text(encoding="utf-8")
return BeautifulSoup(html, "html.parser")
Warm-up

The next field of products_page_1.json holds the URL of page 2. Read it from the file, split it into its parts and print the path on one line and the two query parameters as integers on the next.

Expected output
/v1/products
page=2 per_page=10
Starter
next_url = load_json("products_page_1.json")["next"]
# TODO: split the URL with urlsplit()
# TODO: read page and per_page with parse_qs() and convert them to int
# TODO: print the path, then "page=... per_page=..."
Hint 1

urlsplit(url) returns an object with .path and .query.

Hint 2

parse_qs("page=2&per_page=10") returns {'page': ['2'], 'per_page': ['10']}: a list of strings per name. Take element [0] and convert it with int().

Solution
next_url = load_json("products_page_1.json")["next"]
parts = urlsplit(next_url)
query = parse_qs(parts.query)
page = int(query["page"][0])
per_page = int(query["per_page"][0])
print(parts.path)
print(f"page={page} per_page={per_page}")
assert (page, per_page) == (2, 10)
assert parts.netloc == "api.example.com"
Output
/v1/products
page=2 per_page=10

How it works:

  1. urlsplit() cuts the URL at ://, the first / and the ?. The path is /v1/products.
  2. parse_qs() decodes the query string into a dict of lists, because one name can appear several times.
  3. Query values are always text, so int() converts them before you compare or calculate.

Alternative: httpx parses URLs too. httpx.URL(next_url).params is a read-only mapping with one string per name:

url = httpx.URL(next_url)
print(url.path, url.params["page"], url.params["per_page"])
Output
/v1/products 2 10

M16-W02 · Decide what to do with a status code

Section titled “M16-W02 · Decide what to do with a status code”
Warm-up

Write action_for(status) that returns "read" for 2xx, "follow" for 3xx, "retry later" for 429 and 5xx, and "fix request" for every other 4xx. Print each code of codes with its reason phrase from HTTPStatus and its action, as in the expected output.

Expected output
200 OK -> read
204 No Content -> read
301 Moved Permanently -> follow
400 Bad Request -> fix request
401 Unauthorized -> fix request
404 Not Found -> fix request
422 Unprocessable Content -> fix request
429 Too Many Requests -> retry later
500 Internal Server Error -> retry later
503 Service Unavailable -> retry later
Starter
from http import HTTPStatus
codes = [200, 204, 301, 400, 401, 404, 422, 429, 500, 503]
def action_for(status: int) -> str:
# TODO: decide by the status class (status // 100); 429 is special
...
# TODO: print "code phrase -> action" for each code
Hint 1

status // 100 gives the class: 2, 3, 4 or 5. Test for 429 before the general 4xx rule.

Hint 2

HTTPStatus(404).phrase is 'Not Found'. Pad it with :<22 in an f-string to line up the arrows.

Solution
from http import HTTPStatus
codes = [200, 204, 301, 400, 401, 404, 422, 429, 500, 503]
def action_for(status: int) -> str:
if status == 429 or status // 100 == 5:
return "retry later"
match status // 100:
case 2:
return "read"
case 3:
return "follow"
case 4:
return "fix request"
raise ValueError(f"unexpected status {status}")
for code in codes:
print(f"{code} {HTTPStatus(code).phrase:<22} -> {action_for(code)}")
assert action_for(429) == "retry later"
assert action_for(422) == "fix request"
assert [action_for(c) for c in (204, 301, 503)] == ["read", "follow", "retry later"]
Output
200 OK -> read
204 No Content -> read
301 Moved Permanently -> follow
400 Bad Request -> fix request
401 Unauthorized -> fix request
404 Not Found -> fix request
422 Unprocessable Content -> fix request
429 Too Many Requests -> retry later
500 Internal Server Error -> retry later
503 Service Unavailable -> retry later

How it works:

  1. The special cases come first: 429 and all 5xx codes are transient, so the client waits and retries.
  2. match on the class handles the rest. Any other 4xx means that the request itself is wrong.
  3. A status outside 2xx–5xx (such as 1xx) raises, so a surprise never passes silently. On Python 3.12, HTTPStatus(422).phrase is the older Unprocessable Entity.

Alternative: httpx answers the class questions for you on a response: response.is_success, response.is_redirect, response.is_client_error and response.is_server_error.

M16-W03 · Predict the output: JSON to Python

Section titled “M16-W03 · Predict the output: JSON to Python”
Warm-up

Predict the output: write down what each line prints. Then run the code and compare.

Acceptance criteria:

  • Write your prediction for every line before you run the code.
  • Run the code. Your prediction matches the Output in the solution, line by line.
  • For each line you got wrong, you can name the JSON rule that explains it.
Starter
raw = (
'{"id": "P019", "stock": 0, "price": 99.99, "in_stock": false,'
' "next": null, "tags": ["sports"], "launch_date": "2023-05-02"}'
)
record = json.loads(raw)
for key, value in record.items():
print(key, type(value).__name__, value)
print(bool(record["stock"]), record["next"] is None)
print(json.dumps({"in_stock": True, "discount": None, "name": "Café"}))
# TODO: write your prediction for each line before you run it
Hint 1

false, null and arrays have Python equivalents with other names. JSON has no date type.

Solution
raw = (
'{"id": "P019", "stock": 0, "price": 99.99, "in_stock": false,'
' "next": null, "tags": ["sports"], "launch_date": "2023-05-02"}'
)
record = json.loads(raw)
for key, value in record.items():
print(key, type(value).__name__, value)
print(bool(record["stock"]), record["next"] is None)
print(json.dumps({"in_stock": True, "discount": None, "name": "Café"}))
assert record["in_stock"] is False and record["next"] is None
assert isinstance(record["launch_date"], str)
Output
id str P019
stock int 0
price float 99.99
in_stock bool False
next NoneType None
tags list ['sports']
launch_date str 2023-05-02
False True
{"in_stock": true, "discount": null, "name": "Caf\u00e9"}

How it works:

  1. false becomes False, null becomes None and the array becomes a list.
  2. 0 has no dot, so it is an int; 99.99 is a float. A stock of 0 is falsy, which is why bool(record["stock"]) is False.
  3. "2023-05-02" stays a str: JSON has no date type.
  4. json.dumps() goes the other way: True becomes true and None becomes null. By default it escapes non-ASCII characters, so é becomes \u00e9. Pass ensure_ascii=False to keep Café readable.
Warm-up

From products_page_2.json, print the id, name and average rating of every product rated 3.9 or higher, then the number of such products. Read the rating from the nested rating object.

Expected output
P012 Merino Wool Sweater 4.0
P014 Running Socks 3-Pack 3.9
P016 Trail Running Shoes 3.9
P018 Adjustable Dumbbells 4.3
P020 2-Person Camping Tent 3.9
5 products rated 3.9 or higher
Starter
page = load_json("products_page_2.json")
# TODO: loop over page["data"], read item["rating"]["average"]
# TODO: print matching products and the count
Hint 1

The rating is two levels deep: item["rating"]["average"].

Hint 2

Collect the matches in a list first, then print them and len() of the list.

Solution
page = load_json("products_page_2.json")
top = [item for item in page["data"] if item["rating"]["average"] >= 3.9]
for item in top:
print(f"{item['id']} {item['name']:<24} {item['rating']['average']}")
print(len(top), "products rated 3.9 or higher")
assert all(item["rating"]["average"] >= 3.9 for item in top)
assert [item["id"] for item in top][0] == "P012"
Output
P012 Merino Wool Sweater 4.0
P014 Running Socks 3-Pack 3.9
P016 Trail Running Shoes 3.9
P018 Adjustable Dumbbells 4.3
P020 2-Person Camping Tent 3.9
5 products rated 3.9 or higher

How it works:

  1. A comprehension keeps the items whose nested average passes the test.
  2. Each item["rating"] is a dict, so a second ["average"] reaches the number.
  3. Single quotes inside the f-string’s braces avoid a clash with the double quotes around it.

Alternative: if some records could miss the rating object, read it defensively: item.get("rating", {}).get("average", 0).

M16-W05 · Send query parameters with httpx

Section titled “M16-W05 · Send query parameters with httpx”
Warm-up

Use make_client() to request page 3 of /products with 10 items per page. Pass the parameters with params=, not in the URL. Print the final URL, the status, the first and last product ids and the value of next.

Expected output
https://api.example.com/v1/products?page=3&per_page=10
200 P021 P030 None
Starter
client = make_client()
# TODO: client.get("/products", params=...)
# TODO: print response.url, the status, the first and last id and page["next"]
Hint 1

params={"page": 3, "per_page": 10}. httpx converts the numbers to text and builds the query string.

Solution
with make_client() as client:
response = client.get("/products", params={"page": 3, "per_page": 10})
page = response.json()
print(response.url)
print(response.status_code, page["data"][0]["id"], page["data"][-1]["id"], page["next"])
assert response.is_success and page["next"] is None
assert response.url.params["page"] == "3"
Output
https://api.example.com/v1/products?page=3&per_page=10
200 P021 P030 None

How it works:

  1. base_url plus the path /products gives the full URL, and params adds ?page=3&per_page=10.
  2. response.url shows the URL that was really requested. It is the first thing to print when an API returns something unexpected.
  3. next is None on the last page: JSON null.
  4. The with block closes the client. The response object stays usable after that, because httpx has already read its body.

Alternative: httpx.get(url, params=...) sends one request without a client. It has no transport argument, so it always uses the network. Prefer a client: you can test it with a fake transport, and it reuses connections across calls.

Warm-up

Fix the bug: this code should print the number of products on page 1, but it crashes with TypeError: 'method' object is not subscriptable. Find the cause and fix it.

Expected output
10 products on page 1
Starter
with make_client() as client:
response = client.get("/products", params={"page": 1})
body = response.json
print(len(body["data"]), "products on page", body["page"])
# TODO: fix the bug
Hint 1

Print type(body). Is it a dict?

Hint 2

response.json is a method. A method does nothing until you call it with parentheses.

Solution
with make_client() as client:
response = client.get("/products", params={"page": 1})
response.raise_for_status()
body = response.json()
print(len(body["data"]), "products on page", body["page"])
assert isinstance(body, dict) and body["page"] == 1
Output
10 products on page 1

How it works:

  1. Without (), body is the method object itself, not the parsed JSON. Indexing a method with ["data"] raises the TypeError.
  2. response.json() calls the method, which parses the body into a dict.
  3. The fix also adds raise_for_status(), so an error status fails with a clear message instead of a KeyError later.

Alternative: json.loads(response.text) parses the body by hand. It gives the same dict; response.json() is shorter.

M16-W07 · Read an API key without showing it

Section titled “M16-W07 · Read an API key without showing it”
Warm-up

Write get_key(name), which returns the value of an environment variable or raises RuntimeError with a message that names the variable. Write mask(secret), which keeps only the last 3 characters. The solution sets WEATHER_API_KEY itself to stand in for export in a terminal. Print the masked key, then catch and print the error for the missing variable MAPS_API_KEY.

Expected output
WEATHER_API_KEY = *************q20
error: environment variable MAPS_API_KEY is not set
Starter
os.environ["WEATHER_API_KEY"] = "wx_demo_93KfLq20" # stands in for export
def get_key(name: str) -> str:
# TODO: os.environ.get(); raise RuntimeError if missing or empty
...
def mask(secret: str) -> str:
# TODO: stars instead of everything except the last 3 characters
...
# TODO: print the masked WEATHER_API_KEY; try MAPS_API_KEY and print the error
Hint 1

os.environ.get(name) returns None for a missing variable. if not value: also catches an empty string.

Hint 2

"*" * (len(secret) - 3) + secret[-3:] keeps the length visible and hides the rest.

Solution
os.environ["WEATHER_API_KEY"] = "wx_demo_93KfLq20" # stands in for export
os.environ.pop("MAPS_API_KEY", None) # make sure the demo variable is missing
def get_key(name: str) -> str:
value = os.environ.get(name)
if not value:
raise RuntimeError(f"environment variable {name} is not set")
return value
def mask(secret: str) -> str:
return "*" * (len(secret) - 3) + secret[-3:]
key = get_key("WEATHER_API_KEY")
print("WEATHER_API_KEY =", mask(key))
try:
get_key("MAPS_API_KEY")
except RuntimeError as exc:
print("error:", exc)
assert mask(key).endswith("q20") and "93Kf" not in mask(key)
assert len(mask(key)) == len(key)
Output
WEATHER_API_KEY = *************q20
error: environment variable MAPS_API_KEY is not set

How it works:

  1. os.environ is a dict-like view of the environment variables. .get() returns None when the name is missing instead of raising KeyError.
  2. The error message names the variable, so the user knows what to set. It never contains a key.
  3. mask() keeps the length and the last characters: enough to tell two keys apart, not enough to use one.

Alternative: os.environ["WEATHER_API_KEY"] raises KeyError: 'WEATHER_API_KEY' for a missing variable. That works, but the custom message explains the fix better.

Warm-up

Parse data/api/catalog.html with catalog_soup(). Print the page title, the number of product cards (article.product-card), the number of elements with class price, the href of the pagination link with rel="next" and the footer text.

Expected output
Maple & Finch Market | Product catalog
12 cards, 24 price elements
/catalog?page=2
© 2024 Maple & Finch Market Prices in USD.
Starter
soup = catalog_soup()
# TODO: title, len of select("article.product-card"), len of select(".price")
# TODO: the next link's href, the footer text with get_text(strip=True)
Hint 1

soup.select(css) returns a list; len() counts it. soup.title.get_text() reads the title.

Hint 2

soup.find("a", rel="next") or soup.select_one('a[rel="next"]') finds the link. Read the attribute with ["href"].

Solution
soup = catalog_soup()
cards = soup.select("article.product-card")
prices = soup.select(".price")
next_link = soup.select_one('a[rel="next"]')
print(soup.title.get_text())
print(len(cards), "cards,", len(prices), "price elements")
print(next_link["href"])
print(soup.footer.get_text(strip=True))
assert len(cards) == 12 and len(prices) == 24
assert next_link["href"] == "/catalog?page=2"
Output
Maple & Finch Market | Product catalog
12 cards, 24 price elements
/catalog?page=2
© 2024 Maple & Finch Market Prices in USD.

How it works:

  1. .price matches every element with that class: 12 <td class="price"> cells in the table and 12 <span class="price"> in the cards. A selector that is too broad counts things twice; table .price or span.price narrows it.
  2. price-old is a different class, so .price does not match the 3 old prices.
  3. BeautifulSoup decodes the entities &amp; and &copy; into & and ©.

Alternative: soup.find_all("article", class_="product-card") finds the cards without CSS. The argument is class_ with an underscore, because class is a Python keyword.

Core

Write flatten_product(item) that returns a flat dict with the keys id, name, category, price, currency, in_stock, stock, rating and reviews. Apply it to every product on page 3 and print the first three records as aligned lines, then the number of records and their keys.

Expected output
P021 Harbor Lane Mysteries 16.99 4.2 (115)
P022 Weeknight Kitchen Cookbook 29.99 4.0 (92)
P023 A Brief History of Maps 24.50 3.7 (68)
10 records with keys:
['id', 'name', 'category', 'price', 'currency', 'in_stock', 'stock', 'rating', 'reviews']
Starter
def flatten_product(item: dict[str, Any]) -> dict[str, Any]:
# TODO: pick the nine fields, reading price and rating from the nested dicts
...
page = load_json("products_page_3.json")
# TODO: records = [...]; print three lines, the count and the keys
Hint 1

item["price"]["amount"] and item["rating"]["count"] reach the nested numbers. Rename them as you copy them.

Hint 2

Print with an f-string such as f"{r['id']} {r['name']:<28} {r['price']:>7.2f} ...".

Solution
def flatten_product(item: dict[str, Any]) -> dict[str, Any]:
return {
"id": item["id"],
"name": item["name"],
"category": item["category"],
"price": item["price"]["amount"],
"currency": item["price"]["currency"],
"in_stock": item["in_stock"],
"stock": item["stock"],
"rating": item["rating"]["average"],
"reviews": item["rating"]["count"],
}
page = load_json("products_page_3.json")
records = [flatten_product(item) for item in page["data"]]
for r in records[:3]:
name, price = r["name"], r["price"]
print(f"{r['id']} {name:<28} {price:>7.2f} {r['rating']} ({r['reviews']})")
print(len(records), "records with keys:")
print(list(records[0]))
assert all(isinstance(r["price"], float) for r in records)
assert {r["category"] for r in records} == {"Books", "Beauty"}
Output
P021 Harbor Lane Mysteries 16.99 4.2 (115)
P022 Weeknight Kitchen Cookbook 29.99 4.0 (92)
P023 A Brief History of Maps 24.50 3.7 (68)
10 records with keys:
['id', 'name', 'category', 'price', 'currency', 'in_stock', 'stock', 'rating', 'reviews']

How it works:

  1. Each key of the output is chosen and named on purpose. price is clearer than price_amount, and reviews says what the count counts.
  2. Explicit flattening fails loudly with a KeyError if the API drops a field. That is often what you want in a pipeline.
  3. The result is tidy: one dict per product, the same 9 keys in each.

Alternative: pd.json_normalize(page["data"], sep="_") flattens every nested field automatically. Then rename the columns with .rename(columns={"price_amount": "price", ...}).

M16-C02 · Download all pages by page number

Section titled “M16-C02 · Download all pages by page number”
Core

The first response tells you total_pages. Request page 1, then request pages 2 to total_pages in a loop, and collect all product ids. Count the requests with a small wrapper around shop_api. Print the number of requests, the number of ids and the first and last id.

Expected output
requests: 3
30 ids from P001 to P030
Starter
requests_made = 0
def counting_api(request: httpx.Request) -> httpx.Response:
# TODO: count the request, then return shop_api(request)
...
with make_client(counting_api) as client:
# TODO: get page 1, read total_pages, loop over the other pages
...
Hint 1

Use global requests_made inside the wrapper to change the counter.

Hint 2

for number in range(2, first["total_pages"] + 1): visits the remaining pages.

Solution
requests_made = 0
def counting_api(request: httpx.Request) -> httpx.Response:
global requests_made
requests_made += 1
return shop_api(request)
with make_client(counting_api) as client:
first = client.get("/products", params={"page": 1}).raise_for_status().json()
ids = [item["id"] for item in first["data"]]
for number in range(2, first["total_pages"] + 1):
response = client.get("/products", params={"page": number})
page = response.raise_for_status().json()
ids.extend(item["id"] for item in page["data"])
print("requests:", requests_made)
print(len(ids), "ids from", ids[0], "to", ids[-1])
assert len(ids) == len(set(ids)) == first["total"]
assert requests_made == first["total_pages"]
Output
requests: 3
30 ids from P001 to P030

How it works:

  1. Page 1 brings the data and the metadata. total_pages decides how many more requests to send.
  2. raise_for_status() returns the response when the status is fine, so the calls chain into .json().
  3. The asserts check completeness: no missing page, no duplicate id.

Alternative: when you know all page numbers in advance, the requests are independent, so they can run concurrently (M16-X05). A next-link loop cannot, because each request needs the previous answer.

M16-C03 · Fix the bug: the last page goes missing

Section titled “M16-C03 · Fix the bug: the last page goes missing”
Core

Fix the bug: this loop should collect all 30 products by following the next links, but it returns only 20. Find why, and fix it so that it also stops after at most 10 pages.

Expected output
30 items
Starter
with make_client() as client:
page = client.get("/products", params={"page": 1}).json()
items = []
while page["next"]:
items.extend(page["data"])
page = client.get(page["next"]).json()
print(len(items), "items")
# TODO: fix the loop so that the last page is kept; add a 10-page limit
Hint 1

Trace it by hand. When the loop fetches page 3, what is page["next"], and what happens to page 3’s data?

Hint 2

Add the data of a page right after you fetch it, and test for next only afterwards. A for loop over range(10) gives the limit.

Solution
with make_client() as client:
url: str | None = "/products"
params: dict[str, Any] | None = {"page": 1}
items = []
for _ in range(10):
page = client.get(url, params=params).raise_for_status().json()
items.extend(page["data"])
url, params = page["next"], None
if url is None:
break
else:
raise RuntimeError("more than 10 pages; is next always set?")
print(len(items), "items")
assert len(items) == 30
Output
30 items

How it works:

  1. In the buggy loop, fetching page 3 sets page["next"] to None. The while test then ends the loop before page 3’s items are added.
  2. The fix adds the items of every page first, then decides whether to go on. Each page is handled exactly once.
  3. for ... else (module 03) runs the else only when the loop never hit break: after 10 pages that all had a next. That is the safety stop.
  4. params=None after page 1 keeps the query string of the next link. httpx replaces the whole query when you pass params.

Alternative: a generator such as iter_pages() from the lesson hides the loop. Callers then write for page in iter_pages(client, "/products"): and cannot get the order wrong.

M16-C04 · Refactor: a client class for the shop API

Section titled “M16-C04 · Refactor: a client class for the shop API”
Core

Refactor: the procedural code below repeats the base URL, the headers and the status check. Turn it into a class ShopClient that builds one httpx.Client in __init__, offers get_page(number) and iter_products(), and works as a context manager. Print the number of products, the in-stock count and the mean price of the Sports products.

Expected output
30 products, 28 in stock
Sports mean price: 146.79
Starter
# before: repeated settings and checks
transport = httpx.MockTransport(shop_api)
c1 = httpx.Client(base_url=BASE_URL, transport=transport, timeout=10.0)
r1 = c1.get("/products", params={"page": 1})
r1.raise_for_status()
c2 = httpx.Client(base_url=BASE_URL, transport=transport, timeout=10.0)
r2 = c2.get("/products", params={"page": 2})
r2.raise_for_status()
# ... and page 3
class ShopClient:
# TODO: __init__(self, transport), get_page(), iter_products()
# TODO: __enter__ and __exit__ that close the httpx.Client
...
Hint 1

Store the httpx.Client as self._http in __init__. Every method uses it.

Hint 2

iter_products() can be a generator: loop over the pages with get_page() and yield from page["data"]. __exit__ calls self._http.close().

Solution
from types import TracebackType
class ShopClient:
"""A small client for the shop API: shared settings, checks and pagination."""
def __init__(self, transport: httpx.BaseTransport | None = None) -> None:
self._http = httpx.Client(
base_url=BASE_URL,
headers={"Accept": "application/json"},
timeout=10.0,
transport=transport,
)
def get_page(self, number: int) -> dict[str, Any]:
response = self._http.get("/products", params={"page": number})
response.raise_for_status()
return response.json()
def iter_products(self) -> Iterator[dict[str, Any]]:
number = 1
while True:
page = self.get_page(number)
yield from page["data"]
if page["next"] is None:
return
number += 1
def __enter__(self) -> "ShopClient":
return self
def __exit__(
self,
exc_type: type[BaseException] | None,
exc: BaseException | None,
tb: TracebackType | None,
) -> None:
self._http.close()
with ShopClient(transport=httpx.MockTransport(shop_api)) as shop:
products = list(shop.iter_products())
sports = [p["price"]["amount"] for p in products if p["category"] == "Sports"]
print(len(products), "products,", sum(p["in_stock"] for p in products), "in stock")
print(f"Sports mean price: {mean(sports):.2f}")
assert len(products) == 30 and len(sports) == 5
Output
30 products, 28 in stock
Sports mean price: 146.79

How it works:

  1. All shared settings live in one place, __init__. Changing the timeout is a one-line edit.
  2. transport=None is httpx’s default, so production code calls ShopClient() and tests pass the fake transport: dependency injection (module 11).
  3. iter_products() hides pagination. Callers see a stream of products and never deal with pages.
  4. __enter__ and __exit__ (module 11) close the connections even when the block raises. sum() of booleans counts the True values.

Alternative: without a class, a function make_shop_client(transport=None) -> httpx.Client plus a generator function iter_products(client) gives the same reuse. Choose the class when several methods share state.

M16-C05 · Treat 404 as “no such product”

Section titled “M16-C05 · Treat 404 as “no such product””
Core

The endpoint /products/<id> returns one product or 404. Write get_product(client, product_id) that returns the product dict, returns None for a 404, and raises for every other error. Look up P019 and P099 with the fake server, then show that a 500 still raises.

Expected output
Fitness Tracker 0 False
P099: None
raised for 500 /v1/products/P001
Starter
def get_product(client: httpx.Client, product_id: str) -> dict[str, Any] | None:
# TODO: 404 -> None; other errors -> raise_for_status(); else the JSON
...
# TODO: look up P019 and P099; then try a client whose handler returns 500
Hint 1

Check response.status_code == 404 before you call raise_for_status().

Hint 2

For the 500 test, make_client(lambda request: httpx.Response(500)) builds a broken server in one line. Catch httpx.HTTPStatusError and print the status from exc.response.

Solution
def get_product(client: httpx.Client, product_id: str) -> dict[str, Any] | None:
response = client.get(f"/products/{product_id}")
if response.status_code == 404:
return None
response.raise_for_status()
return response.json()
with make_client() as client:
tracker = get_product(client, "P019")
missing = get_product(client, "P099")
print(tracker["name"], tracker["stock"], tracker["in_stock"])
print("P099:", missing)
with make_client(lambda request: httpx.Response(500)) as broken:
try:
get_product(broken, "P001")
except httpx.HTTPStatusError as exc:
print("raised for", exc.response.status_code, exc.request.url.path)
assert tracker["id"] == "P019" and missing is None
Output
Fitness Tracker 0 False
P099: None
raised for 500 /v1/products/P001

How it works:

  1. A 404 for a single record is an expected answer, not a failure: the product does not exist. None says that clearly.
  2. Every other error still raises. A 500 must not look like “no product”, or a server outage would silently empty your dataset.
  3. Product ids are safe in a path. For free text, such as a search term, use params= so that httpx encodes it.

Alternative: try: response.raise_for_status() except httpx.HTTPStatusError as exc: if exc.response.status_code == 404: return None; raise gives the same behavior with EAFP style (module 06).

M16-C06 · Parse Retry-After in both forms

Section titled “M16-C06 · Parse Retry-After in both forms”
Core

Retry-After holds either seconds ("30") or an HTTP date ("Wed, 01 May 2024 12:01:00 GMT"). Write parse_retry_after(value, now) that returns the wait in seconds as a float, 0.0 for a date in the past and None for a missing or unreadable value. Pass now in, so the result is reproducible. Print the result for each test value.

Expected output
'30' -> 30.0
'Wed, 01 May 2024 12:01:00 GMT' -> 45.0
'Wed, 01 May 2024 11:00:00 GMT' -> 0.0
None -> None
'soon' -> None
Starter
from datetime import UTC, datetime
from email.utils import parsedate_to_datetime
now = datetime(2024, 5, 1, 12, 0, 15, tzinfo=UTC)
values = ["30", "Wed, 01 May 2024 12:01:00 GMT", "Wed, 01 May 2024 11:00:00 GMT",
None, "soon"]
def parse_retry_after(value: str | None, now: datetime) -> float | None:
# TODO: digits -> float; else try parsedate_to_datetime; clamp at 0
...
Hint 1

value.isdigit() tests the seconds form. parsedate_to_datetime(value) parses the date form and raises ValueError for garbage.

Hint 2

Subtracting two aware datetimes gives a timedelta; .total_seconds() turns it into a float. max(0.0, ...) clamps past dates.

Solution
from datetime import UTC, datetime
from email.utils import parsedate_to_datetime
now = datetime(2024, 5, 1, 12, 0, 15, tzinfo=UTC)
values = ["30", "Wed, 01 May 2024 12:01:00 GMT", "Wed, 01 May 2024 11:00:00 GMT",
None, "soon"]
def parse_retry_after(value: str | None, now: datetime) -> float | None:
if value is None:
return None
value = value.strip()
if value.isdigit():
return float(value)
try:
when = parsedate_to_datetime(value)
except ValueError:
return None
return max(0.0, (when - now).total_seconds())
for value in values:
print(f"{value!r:<34} -> {parse_retry_after(value, now)}")
assert parse_retry_after("Wed, 01 May 2024 12:01:00 GMT", now) == 45.0
assert parse_retry_after("soon", now) is None
Output
'30' -> 30.0
'Wed, 01 May 2024 12:01:00 GMT' -> 45.0
'Wed, 01 May 2024 11:00:00 GMT' -> 0.0
None -> None
'soon' -> None

How it works:

  1. The seconds form is the common one, so it is tested first and needs no parsing library.
  2. parsedate_to_datetime() reads the HTTP date format and returns an aware datetime in UTC (module 09).
  3. 12:01:00 minus 12:00:15 is 45 seconds. A date in the past means “now”: max() turns the negative wait into 0.
  4. Injecting now makes the function testable. In production, call it with datetime.now(UTC).

Alternative: some APIs skip Retry-After and send X-RateLimit-Reset, a Unix timestamp. Then the wait is reset - now.timestamp(), clamped at 0 in the same way.

M16-C07 · Build a backoff schedule with jitter

Section titled “M16-C07 · Build a backoff schedule with jitter”
Core

Write backoff_schedule(attempts, base, cap, rng=None) that returns the waits before retries 1 to attempts: min(cap, base * 2**(k-1)). With an rng, return full-jitter waits instead: a uniform random value between 0 and the plain wait, rounded to 2 decimals. Print the plain schedule for 6 retries (base 0.5 s, cap 10 s), a jittered one with random.Random(7) and both totals.

Expected output
plain: [0.5, 1.0, 2.0, 4.0, 8.0, 10.0] total 25.5
jittered: [0.16, 0.15, 1.3, 0.29, 4.29, 3.66] total 9.85
Starter
def backoff_schedule(
attempts: int, base: float, cap: float, rng: random.Random | None = None
) -> list[float]:
# TODO: plain waits; with rng, rng.uniform(0, wait) rounded to 2 decimals
...
Hint 1

Build the plain list with a comprehension over range(1, attempts + 1).

Hint 2

Return early when rng is None. Otherwise map each plain wait through round(rng.uniform(0, wait), 2).

Solution
def backoff_schedule(
attempts: int, base: float, cap: float, rng: random.Random | None = None
) -> list[float]:
plain = [min(cap, base * 2 ** (k - 1)) for k in range(1, attempts + 1)]
if rng is None:
return plain
return [round(rng.uniform(0, wait), 2) for wait in plain]
plain = backoff_schedule(6, base=0.5, cap=10.0)
jittered = backoff_schedule(6, base=0.5, cap=10.0, rng=random.Random(7))
print("plain: ", plain, "total", sum(plain))
print("jittered:", jittered, "total", round(sum(jittered), 2))
assert plain == [0.5, 1.0, 2.0, 4.0, 8.0, 10.0]
assert all(0 <= j <= p for j, p in zip(jittered, plain, strict=True))
Output
plain: [0.5, 1.0, 2.0, 4.0, 8.0, 10.0] total 25.5
jittered: [0.16, 0.15, 1.3, 0.29, 4.29, 3.66] total 9.85

How it works:

  1. The plain waits double from 0.5 s until the cap stops them at 10 s.
  2. Full jitter draws each wait between 0 and the plain wait. On average it waits half as long, and clients that failed together no longer retry together.
  3. A seeded random.Random(7) makes the jitter reproducible in a test. Production code uses an unseeded generator.

Alternative: “equal jitter” keeps half of the wait fixed: wait / 2 + rng.uniform(0, wait / 2). It never retries almost at once, which some APIs prefer.

M16-C08 · Retry a flaky forecast endpoint

Section titled “M16-C08 · Retry a flaky forecast endpoint”
Core

The forecast endpoint fails with 503 and then 502 before it answers. Write get_json_with_retry(client, path, max_attempts, sleep) that retries 5xx responses and transport errors with backoff (1, 2, 4 … seconds) and returns the parsed JSON. Pass waits.append as sleep. Print each failed attempt, the waits and the forecast’s location and first daily maximum.

Expected output
attempt 1: 503
attempt 2: 502
waits: [1, 2]
Chicago 20.4
Starter
failures = [503, 502]
def flaky_forecast(request: httpx.Request) -> httpx.Response:
if failures:
return httpx.Response(failures.pop(0))
return shop_api(request)
def get_json_with_retry(
client: httpx.Client, path: str, max_attempts: int = 4,
sleep: Callable[[float], None] = time.sleep,
) -> Any:
# TODO: loop over attempts; retry 5xx and httpx.TransportError; else raise
...
Hint 1

response.is_server_error is True for 5xx. Wait 2 ** (attempt - 1) seconds before the next attempt.

Hint 2

On the last attempt, do not catch anything: call raise_for_status() so the final error reaches the caller.

Solution
failures = [503, 502]
def flaky_forecast(request: httpx.Request) -> httpx.Response:
if failures:
return httpx.Response(failures.pop(0))
return shop_api(request)
def get_json_with_retry(
client: httpx.Client, path: str, max_attempts: int = 4,
sleep: Callable[[float], None] = time.sleep,
) -> Any:
for attempt in range(1, max_attempts + 1):
last = attempt == max_attempts
try:
response = client.get(path)
except httpx.TransportError as exc:
if last:
raise
print(f"attempt {attempt}: {type(exc).__name__}")
else:
if not response.is_server_error or last:
return response.raise_for_status().json()
print(f"attempt {attempt}: {response.status_code}")
sleep(2 ** (attempt - 1))
raise AssertionError("not reached")
waits: list[float] = []
with make_client(flaky_forecast) as client:
forecast = get_json_with_retry(client, "/forecast", sleep=waits.append)
print("waits:", waits)
print(forecast["location"]["name"], forecast["daily"][0]["max_c"])
assert waits == [1, 2] and forecast["daily"][0]["date"] == "2024-05-01"
Output
attempt 1: 503
attempt 2: 502
waits: [1, 2]
Chicago 20.4

How it works:

  1. Each attempt either raises a transport error or returns a response. try/except/else (module 06) separates the two cases.
  2. A success, a 4xx or the last attempt leaves through raise_for_status().json(): data, or an exception.
  3. Only 5xx and transport errors reach sleep(). The waits double: 1 s, then 2 s.
  4. The final raise is unreachable, but it tells readers and type checkers that the loop always returns or raises.

Alternative: in a real project, a library such as tenacity gives retry decorators with backoff, jitter and stop rules. Your own 20 lines are easier to read and test when you need only one policy.

M16-C09 · Interpret a rate-limit response

Section titled “M16-C09 · Interpret a rate-limit response”
Core

Interpret a result: error_429.json is what the shop API sent after a burst of requests. Read it and print four facts: when the window resets, how long to wait before the next request, the steady request spacing that stays under the limit, and how long a 30-page download takes at that spacing. Then print the decision: wait, or fix the request.

Expected output
status 429: rate_limit_exceeded, 0 requests left
window resets at 2024-05-01T12:01:00Z
wait 30 s before the next request
stay under the limit: one request every 1.0 s
30 pages at that pace take 30 s
decision: wait and retry
Starter
body = load_json("error_429.json")
# TODO: read reset_at, retry_after, limit (requests per minute)
# TODO: spacing = 60 / limit seconds; 30 pages * spacing
# TODO: print the facts and the decision
Hint 1

The limit is per minute, so the smallest safe gap between requests is 60 / limit seconds.

Hint 2

A 429 is a timing problem, not a problem with the request. Decide with the status class rules from the lesson.

Solution
body = load_json("error_429.json")
spacing = 60 / body["limit"]
pages = 30
print(f"status {body['status']}: {body['error']}, {body['remaining']} requests left")
print(f"window resets at {body['reset_at']}")
print(f"wait {body['retry_after']} s before the next request")
print(f"stay under the limit: one request every {spacing:.1f} s")
print(f"{pages} pages at that pace take {pages * spacing:.0f} s")
decision = "wait and retry" if body["status"] == 429 else "fix the request"
print("decision:", decision)
assert spacing == 1.0 and decision == "wait and retry"
Output
status 429: rate_limit_exceeded, 0 requests left
window resets at 2024-05-01T12:01:00Z
wait 30 s before the next request
stay under the limit: one request every 1.0 s
30 pages at that pace take 30 s
decision: wait and retry

How it works:

  1. remaining is 0, so the client used up its 60 requests for this minute.
  2. retry_after says 30 seconds. Waiting less earns another 429.
  3. At 60 requests per minute, one request per second never hits the limit. A full download of 30 pages then takes 30 seconds, which is fine for a nightly job.
  4. The request itself was valid, so the decision is to wait, not to change it.

Alternative: with 10 items per page, the same data in pages of 100 (if the API allows per_page=100) would need 1 request instead of 30. Asking for bigger pages is often the easiest way to stay under a rate limit.

Core

Choose a method and justify it: write should_retry(method, outcome) that decides if a failed request may be retried. outcome is a status code or the name of an exception. Retry 429, 5xx, ReadTimeout and ConnectError, but never a 4xx other than 429, and never a POST unless the outcome is ConnectError (the request never reached the server). Print the decision for each case.

Expected output
GET 503 retry
GET 404 do not retry
GET 429 retry
GET ReadTimeout retry
POST 503 do not retry
POST ReadTimeout do not retry
POST ConnectError retry
PUT 500 retry
DELETE 401 do not retry
Starter
IDEMPOTENT = {"GET", "HEAD", "PUT", "DELETE"}
cases = [("GET", 503), ("GET", 404), ("GET", 429), ("GET", "ReadTimeout"),
("POST", 503), ("POST", "ReadTimeout"), ("POST", "ConnectError"),
("PUT", 500), ("DELETE", 401)]
def should_retry(method: str, outcome: int | str) -> bool:
# TODO: transient outcome? then: idempotent method, or POST + ConnectError
...
Hint 1

First decide if the outcome is transient at all. Only then look at the method.

Hint 2

A ReadTimeout on a POST is unsafe: the server may have created the order and only the answer got lost. A ConnectError means that no connection was made, so nothing happened on the server.

Solution
IDEMPOTENT = {"GET", "HEAD", "PUT", "DELETE"}
cases = [("GET", 503), ("GET", 404), ("GET", 429), ("GET", "ReadTimeout"),
("POST", 503), ("POST", "ReadTimeout"), ("POST", "ConnectError"),
("PUT", 500), ("DELETE", 401)]
def is_transient(outcome: int | str) -> bool:
if isinstance(outcome, str):
return outcome in {"ReadTimeout", "ConnectError"}
return outcome == 429 or 500 <= outcome <= 599
def should_retry(method: str, outcome: int | str) -> bool:
if not is_transient(outcome):
return False
return method in IDEMPOTENT or outcome == "ConnectError"
for method, outcome in cases:
verdict = "retry" if should_retry(method, outcome) else "do not retry"
print(f"{method:<7}{outcome!s:<14}{verdict}")
assert should_retry("GET", 429) and not should_retry("GET", 404)
assert not should_retry("POST", "ReadTimeout") and should_retry("POST", "ConnectError")
Output
GET 503 retry
GET 404 do not retry
GET 429 retry
GET ReadTimeout retry
POST 503 do not retry
POST ReadTimeout do not retry
POST ConnectError retry
PUT 500 retry
DELETE 401 do not retry

How it works:

  1. is_transient() encodes the status rules: 429 and 5xx may succeed later; other 4xx codes will not.
  2. Idempotent methods may repeat safely, so every transient failure is retried for them.
  3. A POST is retried only when it surely never arrived. A 503 or a read timeout could come after the server already acted, and a retry could create a duplicate order.
  4. Justification: this policy never duplicates side effects and still recovers from the common transient failures. When an API supports an Idempotency-Key header, a POST with a fixed key becomes safe to retry too.

Alternative: urllib3.util.Retry, which requests uses, has the same knobs: status_forcelist=[429, 500, 502, 503, 504] and allowed_methods (by default the idempotent methods only).

M16-C11 · Hourly weather features for a demand model

Section titled “M16-C11 · Hourly weather features for a demand model”
Core

Fetch /forecast from the fake server. For each hour, compute a temperature band: "cold" below 10 °C, "mild" below 16 °C and "warm" otherwise. Count the hours per band for each day, and count the rainy hours (precipitation_mm > 0) per band. Print one line per day, then the share of rainy hours that were cold.

Expected output
2024-05-01 cold= 7 mild= 8 warm= 9
2024-05-02 cold= 5 mild=10 warm= 9
rainy hours by band: {'mild': 5, 'cold': 5}
cold share of rainy hours: 50%
Starter
def band(temperature: float) -> str:
# TODO: cold / mild / warm
...
with make_client() as client:
forecast = client.get("/forecast").raise_for_status().json()
# TODO: Counter per day of bands; Counter of bands for rainy hours
Hint 1

hour["time"][:10] is the date part of the ISO string. A defaultdict(Counter) keeps one Counter per day.

Hint 2

Print counts["cold"], counts["mild"] and counts["warm"] in a fixed order; a Counter returns 0 for a missing key.

Solution
def band(temperature: float) -> str:
if temperature < 10:
return "cold"
if temperature < 16:
return "mild"
return "warm"
with make_client() as client:
forecast = client.get("/forecast").raise_for_status().json()
per_day: dict[str, Counter[str]] = defaultdict(Counter)
rainy = Counter()
for hour in forecast["hourly"]:
label = band(hour["temperature_c"])
per_day[hour["time"][:10]][label] += 1
if hour["precipitation_mm"] > 0:
rainy[label] += 1
for day, counts in per_day.items():
bands = " ".join(f"{name}={counts[name]:>2}" for name in ("cold", "mild", "warm"))
print(day, bands)
print("rainy hours by band:", dict(rainy))
print(f"cold share of rainy hours: {rainy['cold'] / rainy.total():.0%}")
assert sum(per_day["2024-05-02"].values()) == 24 and rainy.total() == 10
Output
2024-05-01 cold= 7 mild= 8 warm= 9
2024-05-02 cold= 5 mild=10 warm= 9
rainy hours by band: {'mild': 5, 'cold': 5}
cold share of rainy hours: 50%

How it works:

  1. band() turns a number into a category: a common step when you build features from raw readings.
  2. defaultdict(Counter) creates a fresh Counter the first time a day appears.
  3. All 10 rainy hours fall on May 2. Counter.total() sums the counts.
  4. The ISO time string is safe to slice here because every value has the same fixed format and no offset.

Alternative: with pandas, pd.cut(df["temperature_c"], [-50, 10, 16, 50], right=False, labels=["cold", "mild", "warm"]) makes the bands, and pd.crosstab(df["date"], df["band"]) counts them.

M16-C12 · Scrape the Electronics price list to CSV

Section titled “M16-C12 · Scrape the Electronics price list to CSV”
Core

From the price table in catalog.html, build one record per row with the keys from the header row (lower case). Read the id from the row’s data-id attribute, convert the price text to a float and keep only Electronics. Sort by price, highest first, write output/electronics_prices.csv and print the file.

Expected output
id,product,category,price,stock
P003,55-inch 4K Smart TV,Electronics,1299.0,In stock
P004,14-inch Ultrabook Laptop,Electronics,1149.0,In stock
P002,Noise-Cancelling Headphones,Electronics,249.0,In stock
P005,Smartwatch Series 5,Electronics,199.99,In stock
P001,Wireless Earbuds,Electronics,79.99,In stock
Starter
soup = catalog_soup()
table = soup.select_one("table#products")
# TODO: headers from thead th; one dict per tbody tr; price -> float
# TODO: filter Electronics, sort by price descending, write and print the CSV
Hint 1

dict(zip(headers, cells, strict=True)) pairs header names with cell texts. tr["data-id"] reads the attribute.

Hint 2

float(text.removeprefix("$").replace(",", "")) converts $1,299.00. Sort with key=lambda r: r["price"], reverse=True.

Solution
soup = catalog_soup()
table = soup.select_one("table#products")
headers = [th.get_text(strip=True).lower() for th in table.select("thead th")]
rows = []
for tr in table.select("tbody tr"):
cells = [td.get_text(strip=True) for td in tr.find_all("td")]
record = dict(zip(headers, cells, strict=True))
record["id"] = tr["data-id"]
record["price"] = float(record["price"].removeprefix("$").replace(",", ""))
rows.append(record)
electronics = sorted(
(r for r in rows if r["category"] == "Electronics"),
key=lambda r: r["price"],
reverse=True,
)
out = Path("output")
out.mkdir(exist_ok=True)
path = out / "electronics_prices.csv"
with path.open("w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=headers)
writer.writeheader()
writer.writerows(electronics)
print(path.read_text(encoding="utf-8"), end="")
assert [r["id"] for r in electronics][:2] == ["P003", "P004"]
assert len(rows) == 12 and len(electronics) == 5
Output
id,product,category,price,stock
P003,55-inch 4K Smart TV,Electronics,1299.0,In stock
P004,14-inch Ultrabook Laptop,Electronics,1149.0,In stock
P002,Noise-Cancelling Headphones,Electronics,249.0,In stock
P005,Smartwatch Series 5,Electronics,199.99,In stock
P001,Wireless Earbuds,Electronics,79.99,In stock

How it works:

  1. The header row gives the keys, so the code survives a reordering of the columns.
  2. The data-id attribute is the stable machine id; the first cell shows the same value as text for people.
  3. The price arrives as display text. Stripping the $ and the thousands separator turns it into a number that sorts correctly: as text, "$79.99" would sort above "$1,299.00".
  4. print(..., end="") avoids a blank line, because the file already ends with a line break.

Alternative: pd.read_html() reads every <table> of a page into DataFrames in one call, but it needs the lxml or html5lib package. BeautifulSoup gives you control over attributes such as data-id, which read_html drops.

M16-C13 · Ratings and reviews from the product cards

Section titled “M16-C13 · Ratings and reviews from the product cards”
Core

From the 12 product cards, read the id (data-product-id), the rating (data-rating on span.rating), the review count from text such as (216 reviews) and the stock state from the class of p.stock (in or out). Print the 3 cards with the most reviews, the out-of-stock ids and the review-weighted mean rating.

Expected output
P001 216 reviews rating 3.8
P010 166 reviews rating 3.9
P002 141 reviews rating 3.9
out of stock: ['P006']
weighted mean rating: 3.85 over 1239 reviews
Starter
soup = catalog_soup()
cards = []
for card in soup.select("article.product-card"):
# TODO: id, rating (float), reviews (int), in_stock (bool from the class list)
...
# TODO: top 3 by reviews, out-of-stock ids, weighted mean rating
Hint 1

card.select_one("p.stock")["class"] is a list such as ['stock', 'in']. Test "in" in ....

Hint 2

"(216 reviews)".strip("()").split()[0] gives "216". The weighted mean is sum(rating * reviews) / sum(reviews).

Solution
soup = catalog_soup()
cards = []
for card in soup.select("article.product-card"):
reviews_text = card.select_one("span.reviews").get_text(strip=True)
cards.append({
"id": card["data-product-id"],
"rating": float(card.select_one("span.rating")["data-rating"]),
"reviews": int(reviews_text.strip("()").split()[0]),
"in_stock": "in" in card.select_one("p.stock")["class"],
})
top = sorted(cards, key=lambda c: c["reviews"], reverse=True)[:3]
for c in top:
print(f"{c['id']} {c['reviews']:>4} reviews rating {c['rating']}")
print("out of stock:", [c["id"] for c in cards if not c["in_stock"]])
total_reviews = sum(c["reviews"] for c in cards)
weighted = sum(c["rating"] * c["reviews"] for c in cards) / total_reviews
print(f"weighted mean rating: {weighted:.2f} over {total_reviews} reviews")
assert top[0]["id"] == "P001" and len(cards) == 12
Output
P001 216 reviews rating 3.8
P010 166 reviews rating 3.9
P002 141 reviews rating 3.9
out of stock: ['P006']
weighted mean rating: 3.85 over 1239 reviews

How it works:

  1. Attributes carry clean values: data-rating="3.8" is easier to read than the star characters in the text.
  2. class is a multi-valued attribute, so BeautifulSoup returns a list such as ['stock', 'in']. "in" in [...] tests for one whole class name. A substring test on the class text would also match a class such as "in-transit".
  3. The weighted mean gives each product a weight equal to its number of reviews, so a rating based on 216 reviews counts more than one based on 61.

Alternative: select the stock state directly: card.select_one("p.stock.out") is not None is True only for out-of-stock cards.

Challenge

The fake server below rate-limits page 2 once (429 with Retry-After: 30) and fails page 3 once with 503. Write fetch_all_products(client, sleep) that follows the next links, retries 429 (waiting Retry-After) and 5xx (backoff 1, 2, 4 s) up to 4 attempts per page, and returns flat records. Print the server log, the waits, and a per-category table: products, units in stock and mean rating.

Expected output
server: page 1 -> 200
server: page 2 -> 429
server: page 2 -> 200
server: page 3 -> 503
server: page 3 -> 200
waits: [30.0, 1]
category products units rating
Beauty 5 553 3.86
Books 5 683 3.90
Clothing 5 649 3.76
Electronics 5 381 3.84
Home 5 471 3.82
Sports 5 428 3.94
Starter
def make_flaky_server() -> Handler:
seen: Counter[str] = Counter()
def handler(request: httpx.Request) -> httpx.Response:
page = request.url.params.get("page", "1")
seen[page] += 1
if page == "2" and seen[page] == 1:
response = json_file_response(429, "error_429.json", {"Retry-After": "30"})
elif page == "3" and seen[page] == 1:
response = httpx.Response(503)
else:
response = shop_api(request)
print(f" server: page {page} -> {response.status_code}")
return response
return handler
def fetch_all_products(
client: httpx.Client, sleep: Callable[[float], None]
) -> list[dict[str, Any]]:
# TODO: follow next links; per page, retry 429 and 5xx; flatten the items
...
Hint 1

Split the job: a helper get_page(client, url, params, sleep) with the retry loop, and fetch_all_products() with the pagination loop.

Hint 2

In the retry loop, the wait is float(response.headers["Retry-After"]) when that header exists, else 2 ** (attempt - 1).

Hint 3

Group with defaultdict(list) by category, then print len(), sum() of stock and mean() of rating.

Solution
def make_flaky_server() -> Handler:
seen: Counter[str] = Counter()
def handler(request: httpx.Request) -> httpx.Response:
page = request.url.params.get("page", "1")
seen[page] += 1
if page == "2" and seen[page] == 1:
response = json_file_response(429, "error_429.json", {"Retry-After": "30"})
elif page == "3" and seen[page] == 1:
response = httpx.Response(503)
else:
response = shop_api(request)
print(f" server: page {page} -> {response.status_code}")
return response
return handler
def get_page(
client: httpx.Client,
url: str,
params: dict[str, Any] | None,
sleep: Callable[[float], None],
max_attempts: int = 4,
) -> dict[str, Any]:
for attempt in range(1, max_attempts + 1):
response = client.get(url, params=params)
retryable = response.status_code == 429 or response.is_server_error
if not retryable or attempt == max_attempts:
return response.raise_for_status().json()
retry_after = response.headers.get("Retry-After")
sleep(float(retry_after) if retry_after else 2 ** (attempt - 1))
raise AssertionError("not reached")
def fetch_all_products(
client: httpx.Client, sleep: Callable[[float], None]
) -> list[dict[str, Any]]:
url: str | None = "/products"
params: dict[str, Any] | None = {"page": 1, "per_page": 10}
records = []
for _ in range(50):
page = get_page(client, url, params, sleep)
records += [
{"id": i["id"], "category": i["category"], "stock": i["stock"],
"rating": i["rating"]["average"]}
for i in page["data"]
]
url, params = page["next"], None
if url is None:
return records
raise RuntimeError("too many pages")
waits: list[float] = []
with make_client(make_flaky_server()) as client:
records = fetch_all_products(client, sleep=waits.append)
print("waits:", waits)
groups: dict[str, list[dict[str, Any]]] = defaultdict(list)
for r in records:
groups[r["category"]].append(r)
print(f"{'category':<12}{'products':>9}{'units':>7}{'rating':>8}")
for category in sorted(groups):
g = groups[category]
print(f"{category:<12}{len(g):>9}{sum(r['stock'] for r in g):>7}"
f"{mean(r['rating'] for r in g):>8.2f}")
assert len(records) == 30 and waits == [30.0, 1]
Output
server: page 1 -> 200
server: page 2 -> 429
server: page 2 -> 200
server: page 3 -> 503
server: page 3 -> 200
waits: [30.0, 1]
category products units rating
Beauty 5 553 3.86
Books 5 683 3.90
Clothing 5 649 3.76
Electronics 5 381 3.84
Home 5 471 3.82
Sports 5 428 3.94

How it works:

  1. get_page() owns the retry policy and fetch_all_products() owns pagination. Each loop is short and testable alone.
  2. Page 2’s first answer is the 429, so the code waits the 30 seconds that Retry-After asks for. Page 3’s 503 has no header, so the first backoff step, 1 second, applies.
  3. The next link of page 2 is followed even though page 2 needed two attempts: the retry happens inside get_page(), and pagination only sees the final good page.
  4. The server log proves the order: every page is requested until it succeeds, and no page is requested after it succeeded.

Alternative: wrap get_page() with the retry decorator of module 11, extended to read Retry-After. Then the pagination code stays the same and the policy is reusable across endpoints.

Challenge

The /users endpoint of secure_server needs Authorization: Bearer <key>. Read the key from MAPLE_API_KEY (the solution sets it to stand in for export). Write fetch_users() that raises PermissionError("API key rejected (401); check MAPLE_API_KEY") on 401 and 403. Build the report lines into a list: active users per city (most first, then by name), the signups per quarter, and the admin usernames. Print the lines, then check that no line contains the key. Show the error with a wrong key too.

Expected output
9 active users of 10
New York 2
Philadelphia 2
Boston 1
Denver 1
Detroit 1
Houston 1
Seattle 1
signups per quarter: {'2023-Q1': 3, '2023-Q2': 3, '2023-Q3': 3, '2023-Q4': 1}
admins: ['yukit']
error: API key rejected (401); check MAPLE_API_KEY
Starter
VALID_KEY = "mf_live_7Q2xK9pL4vR8" # known only to the server
def secure_server(request: httpx.Request) -> httpx.Response:
if request.headers.get("Authorization") != f"Bearer {VALID_KEY}":
return httpx.Response(401, json={"error": "unauthorized"})
return shop_api(request)
os.environ["MAPLE_API_KEY"] = "mf_live_7Q2xK9pL4vR8" # stands in for export
def fetch_users(api_key: str) -> list[dict[str, Any]]:
# TODO: client with the Authorization header; map 401/403 to PermissionError
...
# TODO: build report lines; print them; assert the key is in none of them
Hint 1

Pass headers={"Authorization": f"Bearer {api_key}"} to make_client(), which forwards it to httpx.Client.

Hint 2

Sort the city counts with key=lambda kv: (-kv[1], kv[0]): most users first, ties by name. The quarter of month m is (m - 1) // 3 + 1; the month is created_at[5:7].

Solution
VALID_KEY = "mf_live_7Q2xK9pL4vR8" # known only to the server
def secure_server(request: httpx.Request) -> httpx.Response:
if request.headers.get("Authorization") != f"Bearer {VALID_KEY}":
return httpx.Response(401, json={"error": "unauthorized"})
return shop_api(request)
os.environ["MAPLE_API_KEY"] = "mf_live_7Q2xK9pL4vR8" # stands in for export
def fetch_users(api_key: str) -> list[dict[str, Any]]:
headers = {"Authorization": f"Bearer {api_key}"}
with make_client(secure_server, headers=headers) as client:
response = client.get("/users")
if response.status_code in (401, 403):
raise PermissionError(
f"API key rejected ({response.status_code}); check MAPLE_API_KEY"
)
return response.raise_for_status().json()
api_key = os.environ["MAPLE_API_KEY"]
users = fetch_users(api_key)
active = [u for u in users if u["active"]]
cities = Counter(u["address"]["city"] for u in active)
quarters = Counter(
f"{u['created_at'][:4]}-Q{(int(u['created_at'][5:7]) - 1) // 3 + 1}" for u in users
)
lines = [f"{len(active)} active users of {len(users)}"]
lines += [f" {city:<13}{n}" for city, n in sorted(cities.items(),
key=lambda kv: (-kv[1], kv[0]))]
lines.append(f"signups per quarter: {dict(sorted(quarters.items()))}")
lines.append(f"admins: {[u['username'] for u in users if 'admin' in u['roles']]}")
print("\n".join(lines))
assert not any(api_key in line for line in lines)
try:
fetch_users("mf_live_wrong")
except PermissionError as exc:
print("error:", exc)
Output
9 active users of 10
New York 2
Philadelphia 2
Boston 1
Denver 1
Detroit 1
Houston 1
Seattle 1
signups per quarter: {'2023-Q1': 3, '2023-Q2': 3, '2023-Q3': 3, '2023-Q4': 1}
admins: ['yukit']
error: API key rejected (401); check MAPLE_API_KEY

How it works:

  1. The key travels only in the Authorization header. It never appears in the URL, where server logs and browser history would keep it.
  2. fetch_users() translates 401 and 403 into one clear error that names the variable to check. The message does not echo the key.
  3. Building the report as a list of lines first makes it testable: the assert proves that no line leaks the key before anything is printed.
  4. Sorting by (-count, name) puts the busiest cities first and makes ties reproducible.

Alternative: httpx supports custom authentication classes: subclass httpx.Auth and set the header in auth_flow(). Then httpx.Client(auth=BearerAuth(key)) keeps the header logic in one reusable object.

M16-X03 · Cross-check the web page against the API

Section titled “M16-X03 · Cross-check the web page against the API”
Challenge

The catalog page and the API should agree. Scrape the 12 product cards (id, price, rating, reviews, in stock, old price) and download all 30 products from the API. For each card, compare price, rating, review count and stock with the API record. Print the number of checks per field and any mismatches, then the sale items with their discount, largest discount first (ties by id).

Expected output
12 cards x 4 fields checked against 30 records
mismatches: none
on sale: P002 311.25 -> 249.00 (20.0% off)
on sale: P006 436.25 -> 349.00 (20.0% off)
on sale: P010 87.49 -> 69.99 (20.0% off)
Starter
def parse_price(text: str) -> float:
return float(text.strip().removeprefix("$").replace(",", ""))
# TODO: scrape cards into dicts; fetch all API pages into a dict by id
# TODO: compare the four fields; collect mismatches
# TODO: print the counts, mismatches and sale items
Hint 1

Index the API records by id: api = {item["id"]: item for item in items}. Then each card finds its record in one lookup.

Hint 2

Define the comparisons as a dict of field name to a pair of functions, one for the card and one for the API record. Loop over it for every card.

Solution
def parse_price(text: str) -> float:
return float(text.strip().removeprefix("$").replace(",", ""))
soup = catalog_soup()
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)
cards.append({
"id": card["data-product-id"],
"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]),
"in_stock": "in" in card.select_one("p.stock")["class"],
})
with make_client() as client:
items = []
for number in (1, 2, 3):
response = client.get("/products", params={"page": number})
items += response.raise_for_status().json()["data"]
api = {item["id"]: item for item in items}
fields: dict[str, Callable[[dict[str, Any]], Any]] = {
"price": lambda a: a["price"]["amount"],
"rating": lambda a: a["rating"]["average"],
"reviews": lambda a: a["rating"]["count"],
"in_stock": lambda a: a["in_stock"],
}
mismatches = [
(card["id"], name, card[name], get(api[card["id"]]))
for card in cards
for name, get in fields.items()
if card[name] != get(api[card["id"]])
]
print(f"{len(cards)} cards x {len(fields)} fields checked against {len(api)} records")
print("mismatches:", mismatches or "none")
sales = sorted((c for c in cards if c["old_price"]),
key=lambda c: (-round(1 - c["price"] / c["old_price"], 3), c["id"]))
for c in sales:
print(f"on sale: {c['id']} {c['old_price']:.2f} -> {c['price']:.2f}"
f" ({1 - c['price'] / c['old_price']:.1%} off)")
assert not mismatches and len(sales) == 3
Output
12 cards x 4 fields checked against 30 records
mismatches: none
on sale: P002 311.25 -> 249.00 (20.0% off)
on sale: P006 436.25 -> 349.00 (20.0% off)
on sale: P010 87.49 -> 69.99 (20.0% off)

How it works:

  1. A dict keyed by id turns the join into a lookup: 12 lookups instead of 12 × 30 comparisons.
  2. The fields table maps each card field to the place of the same value in the nested API record. Adding a fifth check is one more line.
  3. The page agrees with the API on all 48 checks. The page adds one fact the API lacks: the old prices.
  4. The discounts print with one decimal. All three are 20.0%: the old prices were set 25% above the sale prices, and 1 − 1/1.25 is 0.2.

Alternative: with pandas, pd.DataFrame(cards).merge(pd.json_normalize(items, sep="_"), on="id", how="left", validate="one_to_one") joins the two sources, and one comparison per column finds the mismatches (module 25).

Challenge

An API allows at most 3 requests in any 10-second window. Write a class SlidingWindowLimiter(limit, window, clock, sleep) whose acquire() method waits just long enough to stay under the limit, using a deque of past request times. Test it with a fake clock: sleep advances the clock instead of waiting. Seven requests arrive at t = 0, 1, 2, 3, 4, 12 and 13 seconds. Print when each request was really sent and how long it waited.

Expected output
arrived 0.0s sent 0.0s waited 0.0s
arrived 1.0s sent 1.0s waited 0.0s
arrived 2.0s sent 2.0s waited 0.0s
arrived 3.0s sent 10.0s waited 7.0s
arrived 4.0s sent 11.0s waited 1.0s
arrived 12.0s sent 12.0s waited 0.0s
arrived 13.0s sent 20.0s waited 7.0s
Starter
from collections import deque
class FakeClock:
def __init__(self) -> None:
self.now = 0.0
def time(self) -> float:
return self.now
def sleep(self, seconds: float) -> None:
self.now += seconds
class SlidingWindowLimiter:
def __init__(self, limit: int, window: float, clock, sleep) -> None:
# TODO: store the settings and a deque of send times
...
def acquire(self) -> float:
# TODO: drop old times; if full, sleep until the oldest leaves the window
# TODO: record the send time; return the wait
...
Hint 1

A request time leaves the window once now - sent >= window. Pop those from the left of the deque first.

Hint 2

If the deque still holds limit times, the wait is sent[0] + window - now. Sleep, then drop the old times again before you record the new one.

Solution
from collections import deque
class FakeClock:
def __init__(self) -> None:
self.now = 0.0
def time(self) -> float:
return self.now
def sleep(self, seconds: float) -> None:
self.now += seconds
class SlidingWindowLimiter:
"""Allow at most `limit` calls in any `window` seconds."""
def __init__(
self,
limit: int,
window: float,
clock: Callable[[], float],
sleep: Callable[[float], None],
) -> None:
self.limit, self.window = limit, window
self.clock, self.sleep = clock, sleep
self.sent: deque[float] = deque()
def _drop_old(self) -> None:
while self.sent and self.clock() - self.sent[0] >= self.window:
self.sent.popleft()
def acquire(self) -> float:
self._drop_old()
wait = 0.0
if len(self.sent) >= self.limit:
wait = self.sent[0] + self.window - self.clock()
self.sleep(wait)
self._drop_old()
self.sent.append(self.clock())
return wait
clock = FakeClock()
limiter = SlidingWindowLimiter(3, 10.0, clock=clock.time, sleep=clock.sleep)
sent_at = []
for arrival in [0, 1, 2, 3, 4, 12, 13]:
clock.now = max(clock.now, arrival) # time moves on until the next request arrives
wait = limiter.acquire()
sent_at.append(clock.now)
print(f"arrived {arrival:>4.1f}s sent {clock.now:>4.1f}s waited {wait:>4.1f}s")
assert all(b - a >= 10 for a, b in zip(sent_at, sent_at[3:]))
Output
arrived 0.0s sent 0.0s waited 0.0s
arrived 1.0s sent 1.0s waited 0.0s
arrived 2.0s sent 2.0s waited 0.0s
arrived 3.0s sent 10.0s waited 7.0s
arrived 4.0s sent 11.0s waited 1.0s
arrived 12.0s sent 12.0s waited 0.0s
arrived 13.0s sent 20.0s waited 7.0s

How it works:

  1. The deque holds the send times inside the current window. Old times leave from the left in O(1), which is why deque (module 09) fits.
  2. Requests 1–3 go out at once. Request 4 arrives at 3 s, but the window from 0 s is full, so it waits until 10 s. Request 5 then waits until 11 s.
  3. At 12 s, the request sent at 2 s has just left the window, so request 6 goes out at once. Request 7 finds sends at 10, 11 and 12 s in the window and waits until 20 s. The assert checks the rule: any 4 consecutive sends span at least 10 seconds.
  4. The fake clock makes the test exact and instant. In production, pass time.monotonic and time.sleep.

Alternative: a token bucket refills tokens at a fixed rate (here 0.3 per second) and allows short bursts up to the bucket size. Many APIs describe their limits this way; the code is about as long.

M16-X05 · Fetch pages concurrently with AsyncClient

Section titled “M16-X05 · Fetch pages concurrently with AsyncClient”
Challenge

When you know all page numbers, the requests are independent and can overlap. Write an async function that fetches pages 1 to 3 with httpx.AsyncClient, at most 2 at a time (asyncio.Semaphore(2)), and returns the products in page order. The async fake server sleeps 10 ms per request and records how many requests were in flight at once. Print the ids count, the first and last id and the peak concurrency.

Expected output
30 items: P001 ... P030
peak requests in flight: 2
Starter
import asyncio
in_flight = 0
peak = 0
async def slow_shop(request: httpx.Request) -> httpx.Response:
global in_flight, peak
in_flight += 1
peak = max(peak, in_flight)
await asyncio.sleep(0.01) # 10 ms of "network"
in_flight -= 1
return shop_api(request)
async def fetch_pages(numbers: list[int], limit: int) -> list[dict[str, Any]]:
# TODO: AsyncClient with MockTransport(slow_shop); a Semaphore(limit)
# TODO: gather one task per page; keep the page order; flatten the items
...
Hint 1

MockTransport accepts an async handler for an AsyncClient. Use async with httpx.AsyncClient(...) as client:.

Hint 2

Inside one task: async with semaphore: response = await client.get(...). asyncio.gather(*tasks) returns the results in the order of the tasks, whatever order they finish in.

Solution
import asyncio
in_flight = 0
peak = 0
async def slow_shop(request: httpx.Request) -> httpx.Response:
global in_flight, peak
in_flight += 1
peak = max(peak, in_flight)
await asyncio.sleep(0.01) # 10 ms of "network"
in_flight -= 1
return shop_api(request)
async def fetch_pages(numbers: list[int], limit: int) -> list[dict[str, Any]]:
semaphore = asyncio.Semaphore(limit)
transport = httpx.MockTransport(slow_shop)
async with httpx.AsyncClient(base_url=BASE_URL, transport=transport) as client:
async def fetch(number: int) -> dict[str, Any]:
async with semaphore:
response = await client.get("/products", params={"page": number})
return response.raise_for_status().json()
pages = await asyncio.gather(*(fetch(n) for n in numbers))
return [item for page in pages for item in page["data"]]
items = asyncio.run(fetch_pages([1, 2, 3], limit=2))
print(len(items), "items:", items[0]["id"], "...", items[-1]["id"])
print("peak requests in flight:", peak)
assert [i["id"] for i in items] == [f"P{n:03d}" for n in range(1, 31)]
assert peak == 2
Output
30 items: P001 ... P030
peak requests in flight: 2

How it works:

  1. asyncio.gather() starts the three fetches together. While one awaits its response, the event loop runs the others (module 15).
  2. The semaphore lets only 2 tasks into the async with semaphore: block at once, so the server never sees more than 2 requests in flight. That is how you respect a concurrency limit.
  3. gather() returns results in task order, so the products stay in page order even if page 3 finishes first.
  4. The 10 ms sleeps are real but tiny. With a real API, 3 pages at 300 ms each take about 0.6 s this way instead of 0.9 s one after another.

Alternative: threads work too: concurrent.futures.ThreadPoolExecutor(max_workers=2).map(fetch_page, [1, 2, 3]) with a normal httpx.Client (module 15). Async scales better to hundreds of requests in flight.