16. APIs and web data — Mini-project
Every Monday, the pricing team of Maple & Finch Market asks for a catalog snapshot. They want one table with every product: its price, stock and rating from the shop API, and its old price from the public catalog page, where the sales are announced. They also want a short report on top.
The API needs a key. It rate-limits bursts with 429 and sometimes times out. The web shop sits behind a proxy that now and then answers 502 Bad Gateway. Your script, catalog_snapshot.py, must survive all of this without help, and must fail with a clear message when it cannot.
The project uses every part of module 16: HTTP requests with httpx, headers and query parameters, status codes, JSON bodies, pagination, retries with backoff and Retry-After, timeouts, an API key from the environment, BeautifulSoup and tidy records written to CSV.
Dataset
Section titled “Dataset”The data comes from two sources:
| Source | URL | Saved copy |
|---|---|---|
| Shop API, 3 pages of 10 products | https://api.example.com/v1/products?page=N&per_page=10 |
data/api/products_page_1.json .. products_page_3.json |
| Rate-limit error body | (sent with a 429) |
data/api/error_429.json |
| Public catalog page, 12 product cards | https://shop.example.com/catalog |
data/api/catalog.html |
The API needs the header Authorization: Bearer <key>. Your key is in the environment variable MAPLE_API_KEY.
Neither server exists, so you develop against a fake. Save this file as fake_server.py next to your script and import make_maple_server from it. It serves the saved files and fails like the real services: the first request for page 2 gets a 429 with Retry-After: 30, the first request for page 3 times out, and the first request for the catalog page gets a 502. It also sets MAPLE_API_KEY, as export MAPLE_API_KEY=... in a terminal would. Pass a list as log, and the server records every request it receives, with a note on whether an Authorization header came with it.
"""fake_server.py: fake Maple & Finch API and web shop for the mini-project."""
import osfrom pathlib import Path
import httpx
API_DIR = Path("data/api")VALID_KEYS = {"mf_live_7Q2xK9pL4vR8"}os.environ.setdefault("MAPLE_API_KEY", "mf_live_7Q2xK9pL4vR8") # stands in for export
def file_response( status: int, name: str, content_type: str, **headers: str) -> httpx.Response: body = (API_DIR / name).read_bytes() return httpx.Response( status, content=body, headers={"Content-Type": content_type, **headers} )
def make_maple_server(log: list[str] | None = None) -> httpx.MockTransport: """Fake api.example.com and shop.example.com, with realistic failures.
If you pass a list as `log`, the server appends one line per request: the host, the path and whether an Authorization header arrived. """ seen: dict[str, int] = {}
def handler(request: httpx.Request) -> httpx.Response: if log is not None: auth = "auth" if "authorization" in request.headers else "no-auth" log.append(f"{request.url.host} {request.url.path} {auth}") key = f"{request.url.host}{request.url.path}?{request.url.params}" seen[key] = seen.get(key, 0) + 1 first = seen[key] == 1 if request.url.host == "shop.example.com" and request.url.path == "/catalog": if first: return httpx.Response(502, text="Bad Gateway") return file_response(200, "catalog.html", "text/html; charset=utf-8") token = request.headers.get("Authorization", "").removeprefix("Bearer ") if token not in VALID_KEYS: return httpx.Response(401, json={"error": "unauthorized"}) if request.url.path == "/v1/products": page = int(request.url.params.get("page", "1")) if page == 2 and first: return file_response( 429, "error_429.json", "application/json", **{"Retry-After": "30"} ) if page == 3 and first: raise httpx.ReadTimeout("read timed out after 10.0s", request=request) if 1 <= page <= 3: name = f"products_page_{page}.json" return file_response(200, name, "application/json") return httpx.Response(404, json={"error": "not_found"})
return httpx.MockTransport(handler)To use the real services later, you pass no transport at all. Nothing else in your script changes.
Requirements
Section titled “Requirements”Your script must:
- Read the key from
MAPLE_API_KEYand stop with a clearRuntimeErrorwhen it is missing. Never print the key. - Use two
httpx.Clientobjects, one per base URL, both with a timeout of 10 seconds (3 seconds to connect) and an injectable transport. The API client has the base URLhttps://api.example.com/v1and the headersAccept: application/json,User-AgentandAuthorization. The web client has the base URLhttps://shop.example.com,Accept: text/htmland the sameUser-Agent, but noAuthorizationheader. httpx sends a client’s headers to every URL that the client requests, also to another host, so a shared client would hand your key to the web shop. Prove the split: the fake server’s request log shows theAuthorizationheader only on requests toapi.example.com. - Send every request through one retry function. It retries
429(waitingRetry-After),5xxand transport errors such as timeouts, with exponential backoff of 1, 2, 4 seconds, and at most 4 attempts. Itssleepfunction is injectable. It prints one line per retry. - Follow the
nextlinks with a safety limit of 20 pages. Check each page’s shape. Check that the number of products equalstotaland that every id is unique. Report the number of pages you really fetched. - Fetch the catalog page with the web client and the same retry function. Check that its content type is HTML. Read each card’s id, price and old price.
- Build one tidy record per API product with these 11 columns:
id,name,category,price,old_price,discount_pct,in_stock,stock,rating,reviews,on_page. Products without a card get an empty old price and discount andon_pageset toFalse. - Check that every card’s price equals the API price.
- Write the records to
output/catalog_snapshot.csv. - Print the report below, exactly.
- End with at least three
assertchecks.
The expected report:
Catalog snapshot: Maple & Finch Market======================================API products: 30 (3 pages)Web page cards: 12 (3 on sale)Requests sent: 7 (waited 32.0 s in retries)Out of stock: P006, P019
category products units mean price mean ratingBeauty 5 553 30.89 3.86Books 5 683 24.29 3.90Clothing 5 649 60.69 3.76Electronics 5 381 595.40 3.84Home 5 471 207.59 3.82Sports 5 428 146.79 3.94
On sale: P002 (-20.0%), P006 (-20.0%), P010 (-20.0%)Saved output/catalog_snapshot.csv: 30 rows, 11 columnsStep plan
Section titled “Step plan”-
Settings and secrets. Write
get_api_key(). Build the two clients inmake_api_client(api_key, transport=None)andmake_web_client(transport=None), so that tests can pass the fake transport. Only the API client gets the key. Count the requests with an httpx event hook: a function that the client calls for every request, set withevent_hooks={"request": [count_request]}. -
The retry function. Write
request_with_retry(client, url, *, params=None, sleep=time.sleep, max_attempts=4). Usetry/except httpx.TransportError/else. WaitRetry-Afterseconds when the header is present, else2 ** (attempt - 1). Let the last attempt raise. -
Pagination. Write a generator
iter_pages(client, sleep)that followsnextlinks, checks each page and yields whole pages, so that the caller can readtotaland count the pages. Sendparamson the first request only. -
Scraping. Fetch
/catalogwith the web client through the retry function, check the content type and parse the cards with BeautifulSoup. Turn$1,299.00into1299.0. -
Join. Index the cards by id and build the 11-column records for the 30 API products. Compute
discount_pctasround(100 * (1 - price / old_price), 1). -
Save and report. Write the CSV with
csv.DictWriter. Print the report with f-strings. UseNonefor missing values:csvwrites it as an empty cell. -
Self-checks. Assert the row count against
total, the unique ids, the price agreement, the waits and that the key never reachedshop.example.com. -
Run it with
python catalog_snapshot.pyand compare every line with the expected report.
A skeleton to start from:
# catalog_snapshot.py: a weekly catalog snapshot from the shop API and web page.import csvimport osimport timefrom pathlib import Path
import httpxfrom bs4 import BeautifulSoup
from fake_server import make_maple_server
API_URL = "https://api.example.com/v1"SHOP_URL = "https://shop.example.com"
# TODO: get_api_key(), make_api_client(), make_web_client(), request_with_retry()# TODO: iter_pages(), parse_catalog()# TODO: build the records, write the CSV, print the report, assertRubric
Section titled “Rubric”| Criterion | Points | Full points when |
|---|---|---|
| Secrets | 2 | The key comes from the environment, a missing key gives a clear error, and no output contains the key |
| Client setup | 2 | One client per base URL with headers, timeout and an injectable transport; the key goes only to the API host |
| Retries | 3 | 429 waits Retry-After; 5xx and timeouts use backoff; 4xx are not retried; the last error propagates; sleep is injected |
| Pagination | 2 | Follows next with a page limit; checks the total and unique ids |
| Scraping | 2 | Uses selectors and attributes, checks the content type, parses prices correctly |
| Tidy output | 2 | 30 records with the 11 columns, empty cells for missing values, CSV written to output/ |
| Report | 2 | The output equals the expected report |
| Self-checks | 1 | At least three meaningful assert statements |
| Total | 16 | 13 or more: you are ready for module 17 |
Stretch goals
Section titled “Stretch goals”- Add jitter to the backoff with an injected
random.Random, and show that the waits stay below the plain schedule. - Respect the rate limit up front: wait at least
60 / 60= 1 second between requests with a throttle (see exercise M16-X04), and count how many 429s disappear. - Cache the API pages on disk in
cache/page_N.json, and read the cache when it is younger than one hour. Make the clock injectable to test it. - Use conditional requests: send
If-None-Matchwith theETagheader of the last response, and treat304 Not Modifiedas “use the cached copy”. Extend the fake server to support it. - Load the CSV with
pd.read_csv()and reproduce the category table withgroupby().agg()(module 25).
Reference solution
Section titled “Reference solution”Try the project yourself first. Then compare your script with this one. Your names can differ; your output must not.
Reference solution
Settings, the key and the client:
import csvimport osimport timefrom collections import defaultdictfrom collections.abc import Callable, Iteratorfrom pathlib import Pathfrom statistics import meanfrom typing import Any
import httpxfrom bs4 import BeautifulSoup
from fake_server import make_maple_server
API_URL = "https://api.example.com/v1"SHOP_URL = "https://shop.example.com"USER_AGENT = "maple-catalog-snapshot/1.0 (data-team@example.org)"TIMEOUT = httpx.Timeout(10.0, connect=3.0)COLUMNS = ["id", "name", "category", "price", "old_price", "discount_pct", "in_stock", "stock", "rating", "reviews", "on_page"]request_log: list[str] = []
def get_api_key(name: str = "MAPLE_API_KEY") -> str: key = os.environ.get(name) if not key: raise RuntimeError(f"Set the {name} environment variable first.") return key
def count_request(request: httpx.Request) -> None: """Event hook: httpx calls it before it sends each request.""" request_log.append(f"{request.method} {request.url.host}{request.url.path}")
def make_api_client( api_key: str, transport: httpx.BaseTransport | None = None) -> httpx.Client: """The only client that carries the key: its headers go to every URL it gets.""" return httpx.Client( base_url=API_URL, headers={ "Accept": "application/json", "User-Agent": USER_AGENT, "Authorization": f"Bearer {api_key}", }, timeout=TIMEOUT, transport=transport, event_hooks={"request": [count_request]}, )
def make_web_client(transport: httpx.BaseTransport | None = None) -> httpx.Client: """A client for the public web shop: no credentials.""" return httpx.Client( base_url=SHOP_URL, headers={"Accept": "text/html", "User-Agent": USER_AGENT}, timeout=TIMEOUT, transport=transport, event_hooks={"request": [count_request]}, )The retry function:
def request_with_retry( client: httpx.Client, url: str, *, params: dict[str, Any] | None = None, sleep: Callable[[float], None] = time.sleep, max_attempts: int = 4,) -> httpx.Response: """GET url; retry 429, 5xx and transport errors; the last error propagates.""" for attempt in range(1, max_attempts): try: response = client.get(url, params=params) except httpx.TransportError as exc: sent, reason, wait = exc.request, type(exc).__name__, 2 ** (attempt - 1) else: if response.status_code != 429 and not response.is_server_error: return response.raise_for_status() retry_after = response.headers.get("Retry-After") sent, reason = response.request, str(response.status_code) wait = float(retry_after) if retry_after else 2 ** (attempt - 1) target = sent.url.raw_path.decode() # path and query string print(f"retry: {target} attempt {attempt} failed ({reason}), waiting {wait:g}s") sleep(wait) return client.get(url, params=params).raise_for_status()Pagination and scraping:
PAGE_KEYS = {"page", "total", "total_pages", "next", "data"}
def iter_pages( client: httpx.Client, sleep: Callable[[float], None], max_pages: int = 20) -> Iterator[dict[str, Any]]: url: str | None = "/products" params: dict[str, Any] | None = {"page": 1, "per_page": 10} for _ in range(max_pages): page = request_with_retry(client, url, params=params, sleep=sleep).json() if missing := PAGE_KEYS - page.keys(): raise ValueError(f"page is missing {sorted(missing)}") yield page # whole pages: the caller needs total and the page count url, params = page["next"], None if url is None: return raise RuntimeError(f"more than {max_pages} pages")
def parse_price(text: str) -> float: return float(text.strip().removeprefix("$").replace(",", ""))
def parse_catalog(html: str) -> dict[str, dict[str, Any]]: soup = BeautifulSoup(html, "html.parser") cards = {} for card in soup.select("article.product-card"): old = card.select_one("span.price-old") cards[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, } return cardsRun the downloads with the fake server and a recording sleep:
waits: list[float] = []server_log: list[str] = [] # what the fake server receivedtransport = make_maple_server(log=server_log)with make_api_client(get_api_key(), transport) as api: pages = list(iter_pages(api, sleep=waits.append))with make_web_client(transport) as web: html_page = request_with_retry(web, "/catalog", sleep=waits.append)if not html_page.headers["content-type"].startswith("text/html"): raise ValueError(f"expected HTML, got {html_page.headers['content-type']}")
products = [item for page in pages for item in page["data"]]total = pages[0]["total"]cards = parse_catalog(html_page.text)print(len(products), "of", total, "products,", len(cards), "cards,", len(request_log), "requests")print("\n".join(sorted(set(server_log))))assert not any(line.startswith("shop.example.com") and line.endswith(" auth") for line in server_log), "the API key leaked to the web shop"retry: /v1/products?page=2&per_page=10 attempt 1 failed (429), waiting 30sretry: /v1/products?page=3&per_page=10 attempt 1 failed (ReadTimeout), waiting 1sretry: /catalog attempt 1 failed (502), waiting 1s30 of 30 products, 12 cards, 7 requestsapi.example.com /v1/products authshop.example.com /catalog no-authJoin, save and report:
records = []for item in products: card = cards.get(item["id"]) old_price = card["old_price"] if card else None price = item["price"]["amount"] records.append({ "id": item["id"], "name": item["name"], "category": item["category"], "price": price, "old_price": old_price, "discount_pct": round(100 * (1 - price / old_price), 1) if old_price else None, "in_stock": item["in_stock"], "stock": item["stock"], "rating": item["rating"]["average"], "reviews": item["rating"]["count"], "on_page": card is not None, })
out_path = Path("output") / "catalog_snapshot.csv"out_path.parent.mkdir(exist_ok=True)with out_path.open("w", newline="", encoding="utf-8") as f: writer = csv.DictWriter(f, fieldnames=COLUMNS) writer.writeheader() writer.writerows(records)
groups: dict[str, list[dict[str, Any]]] = defaultdict(list)for r in records: groups[r["category"]].append(r)on_sale = sorted((r for r in records if r["old_price"]), key=lambda r: r["id"])
title = "Catalog snapshot: Maple & Finch Market"print(title)print("=" * len(title))print(f"API products: {len(records)} ({len(pages)} pages)")print(f"Web page cards: {len(cards)} ({len(on_sale)} on sale)")print(f"Requests sent: {len(request_log)} (waited {sum(waits):.1f} s in retries)")print("Out of stock: ", ", ".join(r["id"] for r in records if not r["in_stock"]))print()print(f"{'category':<12}{'products':>9}{'units':>7}{'mean price':>12}" f"{'mean rating':>13}")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['price'] for r in g):>12.2f}{mean(r['rating'] for r in g):>13.2f}")print()print("On sale:", ", ".join(f"{r['id']} (-{r['discount_pct']}%)" for r in on_sale))rows = out_path.read_text(encoding="utf-8").splitlines()n_columns = len(rows[0].split(","))print(f"Saved {out_path.as_posix()}: {len(rows) - 1} rows, {n_columns} columns")
assert len(records) == len({r["id"] for r in records}) == totalassert all(cards[i]["price"] == r["price"] for r in records if (i := r["id"]) in cards)assert waits == [30.0, 1, 1] and len(request_log) == 7Catalog snapshot: Maple & Finch Market======================================API products: 30 (3 pages)Web page cards: 12 (3 on sale)Requests sent: 7 (waited 32.0 s in retries)Out of stock: P006, P019
category products units mean price mean ratingBeauty 5 553 30.89 3.86Books 5 683 24.29 3.90Clothing 5 649 60.69 3.76Electronics 5 381 595.40 3.84Home 5 471 207.59 3.82Sports 5 428 146.79 3.94
On sale: P002 (-20.0%), P006 (-20.0%), P010 (-20.0%)Saved output/catalog_snapshot.csv: 30 rows, 11 columnsHow it works:
- Secrets. The key is read once and goes only into the
Authorizationheader. httpx shows it as[secure]if anyone prints the headers. The error for a missing key names the variable, not a value. - Clients. One client per base URL. httpx sends a client’s default headers to every request it makes, even to a full URL on another host. With one shared client, the web shop (and every proxy or log on the way) would receive your bearer token. The server log proves the split:
Authorizationarrives only atapi.example.com. The event hookcount_request()sees every request of both clients, including the one that timed out, so the request count is 7: 1 + 2 + 2 API requests and 2 for the catalog page. - Retries. Page 2 waits the 30 seconds that
Retry-Afterasks for. The page 3 timeout and the catalog 502 each wait 1 second, the first backoff step. A 4xx such as a 401 would leave at once throughraise_for_status(), which returns the response when the status is 2xx. - Pagination.
iter_pages()followsnextlinks withparams=Noneafter the first page, checks the shape of each page and stops after 20 pages at most. It yields whole pages, so the script compares the product count withtotaland reports the number of pages it really fetched. - Scraping. The web client asks for
text/htmland carries no key. The content-type check catches a proxy error page that arrives with status 200. - Join.
cards.get(id)returnsNonefor the 18 products that have no card, so their old price and discount stay empty.csvwritesNoneas an empty cell, whichpd.read_csv()reads back as a missing value. - Self-checks. The asserts prove completeness, agreement between the two sources and the retry behavior, including the exact waits.
To run it for real, call make_api_client(get_api_key()) and make_web_client() without a transport and drop sleep=waits.append. Then the script waits 32 seconds in total, as the report says.
Alternative: you can model the two sources as classes, ShopApi and CatalogPage, each with its own client and a fetch() method, and pass both to a build_snapshot() function. Modules 18 and 22 show this design. For a script of this size, functions and one client are easier to read and test.