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:
- Read the task and the expected output.
- Copy the setup block and the starter code into a script, and replace each to-do comment with your code.
- Run the script from your project folder. Compare your output with the expected output.
- 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 csvimport jsonimport osimport randomimport timefrom collections import Counter, defaultdictfrom collections.abc import Callable, Iteratorfrom pathlib import Pathfrom statistics import meanfrom typing import Anyfrom urllib.parse import parse_qs, urlsplit
import httpxfrom 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
Section titled “Warm-up”M16-W01 · Take a next link apart
Section titled “M16-W01 · Take a next link apart”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.
/v1/productspage=2 per_page=10next_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"/v1/productspage=2 per_page=10How it works:
urlsplit()cuts the URL at://, the first/and the?. The path is/v1/products.parse_qs()decodes the query string into a dict of lists, because one name can appear several times.- 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"])/v1/products 2 10M16-W02 · Decide what to do with a status code
Section titled “M16-W02 · Decide what to do with a status code”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.
200 OK -> read204 No Content -> read301 Moved Permanently -> follow400 Bad Request -> fix request401 Unauthorized -> fix request404 Not Found -> fix request422 Unprocessable Content -> fix request429 Too Many Requests -> retry later500 Internal Server Error -> retry later503 Service Unavailable -> retry laterfrom 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 codeHint 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"]200 OK -> read204 No Content -> read301 Moved Permanently -> follow400 Bad Request -> fix request401 Unauthorized -> fix request404 Not Found -> fix request422 Unprocessable Content -> fix request429 Too Many Requests -> retry later500 Internal Server Error -> retry later503 Service Unavailable -> retry laterHow it works:
- The special cases come first: 429 and all 5xx codes are transient, so the client waits and retries.
matchon the class handles the rest. Any other 4xx means that the request itself is wrong.- A status outside 2xx–5xx (such as 1xx) raises, so a surprise never passes silently. On Python 3.12,
HTTPStatus(422).phraseis the olderUnprocessable 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”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.
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 itHint 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 Noneassert isinstance(record["launch_date"], str)id str P019stock int 0price float 99.99in_stock bool Falsenext NoneType Nonetags list ['sports']launch_date str 2023-05-02False True{"in_stock": true, "discount": null, "name": "Caf\u00e9"}How it works:
falsebecomesFalse,nullbecomesNoneand the array becomes alist.0has no dot, so it is anint;99.99is afloat. A stock of 0 is falsy, which is whybool(record["stock"])isFalse."2023-05-02"stays astr: JSON has no date type.json.dumps()goes the other way:TruebecomestrueandNonebecomesnull. By default it escapes non-ASCII characters, soébecomes\u00e9. Passensure_ascii=Falseto keepCaféreadable.
M16-W04 · Read nested fields
Section titled “M16-W04 · Read nested fields”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.
P012 Merino Wool Sweater 4.0P014 Running Socks 3-Pack 3.9P016 Trail Running Shoes 3.9P018 Adjustable Dumbbells 4.3P020 2-Person Camping Tent 3.95 products rated 3.9 or higherpage = load_json("products_page_2.json")# TODO: loop over page["data"], read item["rating"]["average"]# TODO: print matching products and the countHint 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"P012 Merino Wool Sweater 4.0P014 Running Socks 3-Pack 3.9P016 Trail Running Shoes 3.9P018 Adjustable Dumbbells 4.3P020 2-Person Camping Tent 3.95 products rated 3.9 or higherHow it works:
- A comprehension keeps the items whose nested average passes the test.
- Each
item["rating"]is a dict, so a second["average"]reaches the number. - 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”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.
https://api.example.com/v1/products?page=3&per_page=10200 P021 P030 Noneclient = 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 Noneassert response.url.params["page"] == "3"https://api.example.com/v1/products?page=3&per_page=10200 P021 P030 NoneHow it works:
base_urlplus the path/productsgives the full URL, andparamsadds?page=3&per_page=10.response.urlshows the URL that was really requested. It is the first thing to print when an API returns something unexpected.nextisNoneon the last page: JSONnull.- The
withblock 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.
M16-W06 · Fix the bug: a missing call
Section titled “M16-W06 · Fix the bug: a missing call”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.
10 products on page 1with 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 bugHint 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"] == 110 products on page 1How it works:
- Without
(),bodyis the method object itself, not the parsed JSON. Indexing a method with["data"]raises theTypeError. response.json()calls the method, which parses the body into a dict.- The fix also adds
raise_for_status(), so an error status fails with a clear message instead of aKeyErrorlater.
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”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.
WEATHER_API_KEY = *************q20error: environment variable MAPS_API_KEY is not setos.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 errorHint 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 exportos.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)WEATHER_API_KEY = *************q20error: environment variable MAPS_API_KEY is not setHow it works:
os.environis a dict-like view of the environment variables..get()returnsNonewhen the name is missing instead of raisingKeyError.- The error message names the variable, so the user knows what to set. It never contains a key.
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.
M16-W08 · First look at an HTML page
Section titled “M16-W08 · First look at an HTML page”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.
Maple & Finch Market | Product catalog12 cards, 24 price elements/catalog?page=2© 2024 Maple & Finch Market Prices in USD.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) == 24assert next_link["href"] == "/catalog?page=2"Maple & Finch Market | Product catalog12 cards, 24 price elements/catalog?page=2© 2024 Maple & Finch Market Prices in USD.How it works:
.pricematches 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 .priceorspan.pricenarrows it.price-oldis a different class, so.pricedoes not match the 3 old prices.- BeautifulSoup decodes the entities
&and©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.
M16-C01 · Flatten a page of products
Section titled “M16-C01 · Flatten a page of products”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.
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']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 keysHint 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"}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:
- Each key of the output is chosen and named on purpose.
priceis clearer thanprice_amount, andreviewssays what the count counts. - Explicit flattening fails loudly with a
KeyErrorif the API drops a field. That is often what you want in a pipeline. - 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”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.
requests: 330 ids from P001 to P030requests_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"]requests: 330 ids from P001 to P030How it works:
- Page 1 brings the data and the metadata.
total_pagesdecides how many more requests to send. raise_for_status()returns the response when the status is fine, so the calls chain into.json().- 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”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.
30 itemswith 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 limitHint 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) == 3030 itemsHow it works:
- In the buggy loop, fetching page 3 sets
page["next"]toNone. Thewhiletest then ends the loop before page 3’s items are added. - The fix adds the items of every page first, then decides whether to go on. Each page is handled exactly once.
for ... else(module 03) runs theelseonly when the loop never hitbreak: after 10 pages that all had anext. That is the safety stop.params=Noneafter page 1 keeps the query string of thenextlink. httpx replaces the whole query when you passparams.
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”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.
30 products, 28 in stockSports mean price: 146.79# before: repeated settings and checkstransport = 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) == 530 products, 28 in stockSports mean price: 146.79How it works:
- All shared settings live in one place,
__init__. Changing the timeout is a one-line edit. transport=Noneis httpx’s default, so production code callsShopClient()and tests pass the fake transport: dependency injection (module 11).iter_products()hides pagination. Callers see a stream of products and never deal with pages.__enter__and__exit__(module 11) close the connections even when the block raises.sum()of booleans counts theTruevalues.
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””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.
Fitness Tracker 0 FalseP099: Noneraised for 500 /v1/products/P001def 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 500Hint 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 NoneFitness Tracker 0 FalseP099: Noneraised for 500 /v1/products/P001How it works:
- A 404 for a single record is an expected answer, not a failure: the product does not exist.
Nonesays that clearly. - Every other error still raises. A 500 must not look like “no product”, or a server outage would silently empty your dataset.
- 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”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.
'30' -> 30.0'Wed, 01 May 2024 12:01:00 GMT' -> 45.0'Wed, 01 May 2024 11:00:00 GMT' -> 0.0None -> None'soon' -> Nonefrom datetime import UTC, datetimefrom 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, datetimefrom 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.0assert parse_retry_after("soon", now) is None'30' -> 30.0'Wed, 01 May 2024 12:01:00 GMT' -> 45.0'Wed, 01 May 2024 11:00:00 GMT' -> 0.0None -> None'soon' -> NoneHow it works:
- The seconds form is the common one, so it is tested first and needs no parsing library.
parsedate_to_datetime()reads the HTTP date format and returns an awaredatetimein UTC (module 09).- 12:01:00 minus 12:00:15 is 45 seconds. A date in the past means “now”:
max()turns the negative wait into 0. - Injecting
nowmakes the function testable. In production, call it withdatetime.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”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.
plain: [0.5, 1.0, 2.0, 4.0, 8.0, 10.0] total 25.5jittered: [0.16, 0.15, 1.3, 0.29, 4.29, 3.66] total 9.85def 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))plain: [0.5, 1.0, 2.0, 4.0, 8.0, 10.0] total 25.5jittered: [0.16, 0.15, 1.3, 0.29, 4.29, 3.66] total 9.85How it works:
- The plain waits double from 0.5 s until the cap stops them at 10 s.
- 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.
- 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”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.
attempt 1: 503attempt 2: 502waits: [1, 2]Chicago 20.4failures = [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"attempt 1: 503attempt 2: 502waits: [1, 2]Chicago 20.4How it works:
- Each attempt either raises a transport error or returns a response.
try/except/else(module 06) separates the two cases. - A success, a 4xx or the last attempt leaves through
raise_for_status().json(): data, or an exception. - Only 5xx and transport errors reach
sleep(). The waits double: 1 s, then 2 s. - The final
raiseis 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”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.
status 429: rate_limit_exceeded, 0 requests leftwindow resets at 2024-05-01T12:01:00Zwait 30 s before the next requeststay under the limit: one request every 1.0 s30 pages at that pace take 30 sdecision: wait and retrybody = 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 decisionHint 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 = 30print(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"status 429: rate_limit_exceeded, 0 requests leftwindow resets at 2024-05-01T12:01:00Zwait 30 s before the next requeststay under the limit: one request every 1.0 s30 pages at that pace take 30 sdecision: wait and retryHow it works:
remainingis 0, so the client used up its 60 requests for this minute.retry_aftersays 30 seconds. Waiting less earns another 429.- 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.
- 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.
M16-C10 · Choose which requests to retry
Section titled “M16-C10 · Choose which requests to retry”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.
GET 503 retryGET 404 do not retryGET 429 retryGET ReadTimeout retryPOST 503 do not retryPOST ReadTimeout do not retryPOST ConnectError retryPUT 500 retryDELETE 401 do not retryIDEMPOTENT = {"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")GET 503 retryGET 404 do not retryGET 429 retryGET ReadTimeout retryPOST 503 do not retryPOST ReadTimeout do not retryPOST ConnectError retryPUT 500 retryDELETE 401 do not retryHow it works:
is_transient()encodes the status rules: 429 and 5xx may succeed later; other 4xx codes will not.- Idempotent methods may repeat safely, so every transient failure is retried for them.
- A
POSTis 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. - Justification: this policy never duplicates side effects and still recovers from the common transient failures. When an API supports an
Idempotency-Keyheader, aPOSTwith 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”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.
2024-05-01 cold= 7 mild= 8 warm= 92024-05-02 cold= 5 mild=10 warm= 9rainy hours by band: {'mild': 5, 'cold': 5}cold share of rainy hours: 50%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 hoursHint 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() == 102024-05-01 cold= 7 mild= 8 warm= 92024-05-02 cold= 5 mild=10 warm= 9rainy hours by band: {'mild': 5, 'cold': 5}cold share of rainy hours: 50%How it works:
band()turns a number into a category: a common step when you build features from raw readings.defaultdict(Counter)creates a freshCounterthe first time a day appears.- All 10 rainy hours fall on May 2.
Counter.total()sums the counts. - 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”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.
id,product,category,price,stockP003,55-inch 4K Smart TV,Electronics,1299.0,In stockP004,14-inch Ultrabook Laptop,Electronics,1149.0,In stockP002,Noise-Cancelling Headphones,Electronics,249.0,In stockP005,Smartwatch Series 5,Electronics,199.99,In stockP001,Wireless Earbuds,Electronics,79.99,In stocksoup = 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 CSVHint 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) == 5id,product,category,price,stockP003,55-inch 4K Smart TV,Electronics,1299.0,In stockP004,14-inch Ultrabook Laptop,Electronics,1149.0,In stockP002,Noise-Cancelling Headphones,Electronics,249.0,In stockP005,Smartwatch Series 5,Electronics,199.99,In stockP001,Wireless Earbuds,Electronics,79.99,In stockHow it works:
- The header row gives the keys, so the code survives a reordering of the columns.
- The
data-idattribute is the stable machine id; the first cell shows the same value as text for people. - 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". 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”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.
P001 216 reviews rating 3.8P010 166 reviews rating 3.9P002 141 reviews rating 3.9out of stock: ['P006']weighted mean rating: 3.85 over 1239 reviewssoup = 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 ratingHint 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_reviewsprint(f"weighted mean rating: {weighted:.2f} over {total_reviews} reviews")assert top[0]["id"] == "P001" and len(cards) == 12P001 216 reviews rating 3.8P010 166 reviews rating 3.9P002 141 reviews rating 3.9out of stock: ['P006']weighted mean rating: 3.85 over 1239 reviewsHow it works:
- Attributes carry clean values:
data-rating="3.8"is easier to read than the star characters in the text. classis 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".- 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
Section titled “Challenge”M16-X01 · A resilient full download
Section titled “M16-X01 · A resilient full download”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.
server: page 1 -> 200 server: page 2 -> 429 server: page 2 -> 200 server: page 3 -> 503 server: page 3 -> 200waits: [30.0, 1]category products units ratingBeauty 5 553 3.86Books 5 683 3.90Clothing 5 649 3.76Electronics 5 381 3.84Home 5 471 3.82Sports 5 428 3.94def 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] server: page 1 -> 200 server: page 2 -> 429 server: page 2 -> 200 server: page 3 -> 503 server: page 3 -> 200waits: [30.0, 1]category products units ratingBeauty 5 553 3.86Books 5 683 3.90Clothing 5 649 3.76Electronics 5 381 3.84Home 5 471 3.82Sports 5 428 3.94How it works:
get_page()owns the retry policy andfetch_all_products()owns pagination. Each loop is short and testable alone.- Page 2’s first answer is the 429, so the code waits the 30 seconds that
Retry-Afterasks for. Page 3’s 503 has no header, so the first backoff step, 1 second, applies. - The
nextlink of page 2 is followed even though page 2 needed two attempts: the retry happens insideget_page(), and pagination only sees the final good page. - 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.
M16-X02 · An authenticated user report
Section titled “M16-X02 · An authenticated user report”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.
9 active users of 10 New York 2 Philadelphia 2 Boston 1 Denver 1 Detroit 1 Houston 1 Seattle 1signups per quarter: {'2023-Q1': 3, '2023-Q2': 3, '2023-Q3': 3, '2023-Q4': 1}admins: ['yukit']error: API key rejected (401); check MAPLE_API_KEYVALID_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 themHint 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)9 active users of 10 New York 2 Philadelphia 2 Boston 1 Denver 1 Detroit 1 Houston 1 Seattle 1signups per quarter: {'2023-Q1': 3, '2023-Q2': 3, '2023-Q3': 3, '2023-Q4': 1}admins: ['yukit']error: API key rejected (401); check MAPLE_API_KEYHow it works:
- The key travels only in the
Authorizationheader. It never appears in the URL, where server logs and browser history would keep it. fetch_users()translates 401 and 403 into one clear error that names the variable to check. The message does not echo the key.- 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.
- 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”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).
12 cards x 4 fields checked against 30 recordsmismatches: noneon 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)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 itemsHint 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) == 312 cards x 4 fields checked against 30 recordsmismatches: noneon 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:
- A dict keyed by id turns the join into a lookup: 12 lookups instead of 12 × 30 comparisons.
- The
fieldstable maps each card field to the place of the same value in the nested API record. Adding a fifth check is one more line. - The page agrees with the API on all 48 checks. The page adds one fact the API lacks: the old prices.
- 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).
M16-X04 · A client-side rate limiter
Section titled “M16-X04 · A client-side rate limiter”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.
arrived 0.0s sent 0.0s waited 0.0sarrived 1.0s sent 1.0s waited 0.0sarrived 2.0s sent 2.0s waited 0.0sarrived 3.0s sent 10.0s waited 7.0sarrived 4.0s sent 11.0s waited 1.0sarrived 12.0s sent 12.0s waited 0.0sarrived 13.0s sent 20.0s waited 7.0sfrom 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:]))arrived 0.0s sent 0.0s waited 0.0sarrived 1.0s sent 1.0s waited 0.0sarrived 2.0s sent 2.0s waited 0.0sarrived 3.0s sent 10.0s waited 7.0sarrived 4.0s sent 11.0s waited 1.0sarrived 12.0s sent 12.0s waited 0.0sarrived 13.0s sent 20.0s waited 7.0sHow it works:
- 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. - 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.
- 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.
- The fake clock makes the test exact and instant. In production, pass
time.monotonicandtime.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”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.
30 items: P001 ... P030peak requests in flight: 2import asyncio
in_flight = 0peak = 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 = 0peak = 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 == 230 items: P001 ... P030peak requests in flight: 2How it works:
asyncio.gather()starts the three fetches together. While one awaits its response, the event loop runs the others (module 15).- 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. gather()returns results in task order, so the products stay in page order even if page 3 finishes first.- 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.