Part 05 / Stage 2
Working with customer APIs
Goal: Build an API client that survives a real customer API — auth, pagination, rate limits, transient failures — and knows exactly which errors to retry and which to surface. Time: ~3.5 hours · Needs: Python 3.14+, the course venv
Every customer API is different, and imperfect. Acme's simulated API (in tools/fdelab.py) behaves like the real thing: bearer-token auth, pagination, a 429 rate limit with Retry-After, and one transient 503 — so every failure path in this part runs for real, offline.
What you will learn
- Reading API docs, and testing what they claim
- Pagination: page numbers, cursors, and stopping correctly
- Rate limits and retries: 429, Retry-After, exponential backoff with jitter
- Fail fast vs retry: which errors to retry and which to surface
- Idempotency keys for safe write retries
- Webhooks: receiving events and verifying signatures with HMAC
- Concurrency with limits: parallel fetches without flooding the API
Topics in this part
Practice
Work in the course venv. The simulated Acme API is fdelab.customer_api_transport(); check each answer by running it, and compare with solutions/ only after trying.
Exercise 1: Stop correctly
Write count_pages(client) that walks the pagination and returns (pages, rows). Run it against a well-behaved API (rate_limit_every=0, flaky_request=0) and print the result — it must stop because next_page is null, not because of a guessed count.
Show the solution to Exercise 1
# Exercise 1: paginate until the API says stop
import httpx
from fdelab import API_TOKEN, customer_api_transport
def count_pages(client):
page, pages, rows = 1, 0, 0
while page:
body = client.get("/v1/shipments", params={"page": page}).json()
pages += 1
rows += len(body["data"])
page = body["next_page"] # None on the last page -> loop ends
return pages, rows
transport = customer_api_transport(rate_limit_every=0, flaky_request=0)
with httpx.Client(base_url="https://api.acme.example", transport=transport,
headers={"Authorization": f"Bearer {API_TOKEN}"}) as client:
pages, rows = count_pages(client)
print(f"{pages} pages, {rows} rows")
Exercise 2: Backoff with jitter and a budget
Write backoff_waits(attempts, base=1.0, cap=30.0, seed=7) returning the waits for N attempts using exponential backoff capped at cap, each multiplied by jitter drawn from random.uniform(0.5, 1.5) with the given seed. Print the waits for 6 attempts and their total.
Show the solution to Exercise 2
# Exercise 2: exponential backoff, capped, with jitter
import random
def backoff_waits(attempts, base=1.0, cap=30.0, seed=7):
rng = random.Random(seed)
return [round(min(cap, base * 2 ** a) * rng.uniform(0.5, 1.5), 2)
for a in range(attempts)]
waits = backoff_waits(6)
print("waits:", waits)
print("total budget used:", round(sum(waits), 2), "s")
Exercise 3: Force every error path
Using customer_api_transport() defaults, write a client that records every (status, action) pair it sees — e.g. (503, "retried"), (429, "waited"), (200, "ok") — while fetching all pages. Print the event list; it must contain one 503 and one 429.
Show the solution to Exercise 3
# Exercise 3: record every error path the API throws at us
import time
import httpx
from fdelab import API_TOKEN, customer_api_transport
events = []
def get_with_retries(client, params):
for attempt in range(1, 6):
r = client.get("/v1/shipments", params=params)
if r.status_code == 200:
events.append((200, "ok"))
return r
if r.status_code == 429:
events.append((429, "waited"))
time.sleep(float(r.headers.get("Retry-After", 0)))
elif r.status_code in {500, 502, 503, 504}:
events.append((r.status_code, "retried"))
time.sleep(0.01)
else:
r.raise_for_status()
raise RuntimeError("gave up")
with httpx.Client(base_url="https://api.acme.example", transport=customer_api_transport(),
headers={"Authorization": f"Bearer {API_TOKEN}"}) as client:
page, rows = 1, 0
while page:
body = get_with_retries(client, {"page": page}).json()
rows += len(body["data"])
page = body["next_page"]
print("events:", events)
assert (503, "retried") in events and (429, "waited") in events
print("rows:", rows)
Exercise 4: Webhook receiver
Write handle_webhook(body: bytes, signature: str) -> str that returns "accepted" for a verified body and "rejected" otherwise (HMAC-SHA256, shared secret). Show one accepted event and two rejections: a tampered body and a forged signature.
Show the solution to Exercise 4
# Exercise 4: accept verified webhooks, reject everything else
import hashlib, hmac, json
SECRET = b"shared-webhook-secret"
def sign(body: bytes) -> str:
return hmac.new(SECRET, body, hashlib.sha256).hexdigest()
def handle_webhook(body: bytes, signature: str) -> str:
expected = hmac.new(SECRET, body, hashlib.sha256).hexdigest()
return "accepted" if hmac.compare_digest(expected, signature) else "rejected"
body = json.dumps({"event": "shipment.delayed", "id": "S-2004"}).encode()
print("genuine: ", handle_webhook(body, sign(body)))
print("tampered: ", handle_webhook(body.replace(b"S-2004", b"S-1111"), sign(body)))
print("forged sig:", handle_webhook(body, "0" * 64))
Mini-project: The Acme API client
fetch_all_shipments(): every shipment through pagination, retries and the rate limit, with one JSON log line per request (page, status, attempt). It should end by logging rows fetched and requests made.
A solution is in solutions/mini_acme_api_client.py.
Stretch: add jitter, a total time budget, and pytest tests that use the simulated API to force every error path.
Common mistakes
| Mistake | Why it hurts | Fix |
|---|---|---|
| Trusting the docs over the API | The integration breaks on undocumented behaviour | Test every claim with curl first |
| Guessing the page count | Missing or duplicated tail pages | Loop until the API's own stop signal |
| Retrying everything | 401 retries hide config bugs and lock accounts | Retry 429 + 5xx; fail fast otherwise |
| Backoff without jitter | A fleet of clients stampedes in sync | Multiply the wait by a random factor |
| Trusting webhooks unverified | Anyone can POST to your endpoint | HMAC + compare_digest |
| Uncapped parallel fetches | You DoS the customer's API | Semaphore + keep the 429 handling |
Quick recap
- Test what the docs claim; the gaps become your test cases.
- Paginate until the API says there is no more; never guess the page count.
- Retry 429s and 5xx responses with jittered backoff and a retry budget; fail fast on every other 4xx.
- Idempotency keys (or upserts) make write retries safe.
- Verify webhook signatures with HMAC in constant time.
- Cap concurrency with a semaphore — and keep the rate-limit handling.
Checklist
- I fetched all 8 rows through pagination, a 503 and a 429, in 5 requests.
- I can recite the retryable status set and why 401 is not in it.
- I verified a genuine webhook and rejected a tampered one.
- I capped parallel fetches at 2 in flight and saw the peak stay at 2.
- I can explain idempotency keys in two sentences.
Read more: httpx docs · Python hmac · asyncio tasks