Course map
Stage 1: Foundations
Stage 2: Data Integration
Stage 3: Building & Shipping
Stage 4: Customer Engagement
Stage 5: Specialization

Part 05 / Topic 2 of 7

Pagination

APIs return big collections in pages, with two common schemes: page numbers (?page=3) and cursors (?after=abc123, where each response carries the next cursor). Acme's uses page numbers with an explicit next_page that becomes null on the last page — the stopping condition is the part people get wrong. Loop until the API says stop; never guess the page count.

The full loop, with everything from this part wired in:

# examples/01_a_resilient_api_client_auth_pagination.py
import time
import httpx
from fdelab import API_TOKEN, customer_api_transport

RETRYABLE = {429, 500, 502, 503, 504}

def get_with_retries(client, url, params, max_attempts=5):
    for attempt in range(1, max_attempts + 1):
        r = client.get(url, params=params)
        if r.status_code not in RETRYABLE:
            r.raise_for_status()                      # 4xx like 401/404: fail fast
            return r
        wait = float(r.headers.get("Retry-After", 2 ** (attempt - 1) * 0.01))
        print(f"  attempt {attempt}: {r.status_code}, retrying in {wait}s")
        time.sleep(wait)
    raise RuntimeError(f"gave up after {max_attempts} attempts")

def fetch_all(client):
    page, rows = 1, []
    while page:
        body = get_with_retries(client, "/v1/shipments", {"page": page}).json()
        rows.extend(body["data"])
        print(f"page {page}: {len(body['data'])} rows")
        page = body["next_page"]
    return rows

transport = customer_api_transport()
with httpx.Client(base_url="https://api.acme.example", transport=transport,
                  headers={"Authorization": f"Bearer {API_TOKEN}"}, timeout=10) as client:
    rows = fetch_all(client)
print("total rows:", len(rows), "| HTTP requests made:", transport.request_count())
# page 1: 3 rows
#   attempt 1: 503, retrying in 0.01s
# page 2: 3 rows
#   attempt 1: 429, retrying in 0.0s
# page 3: 2 rows
# total rows: 8 | HTTP requests made: 5

Read the output like an engagement log: three pages arrived, but it took five requests — one 503 retried, one 429 waited out via Retry-After. All 8 rows arrived, and every attempt is visible.

🧪 Quick quiz — answer from memory, then check.

  1. How many HTTP requests did the resilient client need to fetch 3 pages, with one 503 and one 429 along the way?
Show the answer

5 — 3 successful pages + 2 retried failures, and all 8 rows arrived. (verified against the example output above)

Done here? The practice set for Part 5 — 4 exercises with solutions — is on the part page.

Search the guide