Chapter 2 · API Design and API Clients
Designing Robust APIs: Pagination, Rate Limits, Retries and Versioning
- Page 5 of 22
- 31 min read
The previous page explained what HTTP promises: safe and idempotent methods, caching, status codes. This page is about what happens when real traffic meets those promises. A list endpoint that returns ten million rows. A client that hammers an API until it is blocked. A network that drops the response after the server has already charged a card. A job that takes four minutes in a request that must answer in thirty seconds. A partner API that changes a field name on a Friday. Every AI product meets all of these: embedding jobs are long, LLM providers rate-limit you hard, and your own API will be called by people who retry.
You will build the server side of each idea in FastAPI and the client side with requests, and you will use the BitByte Practice API (http://localhost:8800, fastapi run practice_api.py --port 8800 in another terminal) as the unreliable third party it was made to be.
What you will learn
- Why offset pagination breaks when data changes, and how to build cursor pagination.
- How rate limits and quotas work, what a
429withRetry-Aftermeans, and how to write a client with exponential backoff, jitter and a retry budget. - How idempotency keys make a
POSTsafe to retry, and how to implement them in FastAPI. - How to run long jobs with
202 Accepted, a status URL and polling, and how to version an API without breaking people. - How to read an OpenAPI contract, tell breaking from non-breaking changes in code, and consume an untrusted external API safely.
Set up the project
One small FastAPI project, grown in two steps. Start with a folder, a virtual environment managed by uv, and the two libraries you need.
mkdir -p ~/projects/robust-api
cd ~/projects/robust-api
uv init --bare
uv add -q "fastapi[standard]" requests
# with pip instead:
# python -m venv .venv && source .venv/bin/activate
# pip install -q "fastapi[standard]" requestsInitialized project `robust-api`The Python snippets on this page continue one another, like cells in a notebook. Run them in uv run python (or Jupyter) from this folder, or paste them into a file and run it with uv run python file.py. Your own server will listen on port 8000.
Pagination: offset or cursor
An endpoint that returns "all items" works on day one and falls over on day ninety. Every list endpoint needs pagination from the start, because adding it later changes the response shape, which is a breaking change (more on that below). There are two main designs.
Offset (?offset=20&limit=10) | Cursor (?cursor=abc&limit=10) | |
|---|---|---|
| Idea | "skip 20 rows, give me 10" | "give me 10 rows after the one I last saw" |
| Jump to page 50 | yes | no: you can only move forward (or back, if you add a previous cursor) |
| Data changes between pages | rows are skipped or repeated | stable |
| Cost on a big table | the database still walks past every skipped row: page 10,000 is slow | an index lookup: page 10,000 costs the same as page 1 |
| Total count | easy (total) | usually omitted (counting is expensive) |
| Good for | small admin tables, "page 3 of 12" interfaces | feeds, logs, chat history, anything large or live, and API clients that crawl everything |
Build both and watch the difference. The data is 25 notes, newest first. The cursor is opaque: clients must treat it as a string to hand back, so you can change what is inside it later (a database id today, a timestamp plus id tomorrow) without breaking anyone.
# file: items.py
import base64
import json
from typing import Annotated
from fastapi import APIRouter, HTTPException, Query
from pydantic import BaseModel
router = APIRouter()
ITEMS = [{"id": number, "title": f"Note {number}"} for number in range(1, 26)]
class Item(BaseModel):
id: int
title: str
class NewItem(BaseModel):
title: str
class OffsetPage(BaseModel):
items: list[Item]
total: int
offset: int
limit: int
class CursorPage(BaseModel):
items: list[Item]
next_cursor: str | None
def newest_first():
return sorted(ITEMS, key=lambda item: item["id"], reverse=True)
def encode_cursor(last_id: int) -> str:
return base64.urlsafe_b64encode(json.dumps({"last_id": last_id}).encode()).decode()
def decode_cursor(cursor: str) -> int:
try:
return int(json.loads(base64.urlsafe_b64decode(cursor.encode()))["last_id"])
except (ValueError, KeyError, TypeError):
raise HTTPException(400, "Invalid cursor")
@router.get("/items", response_model=OffsetPage)
def list_items(
offset: Annotated[int, Query(ge=0)] = 0,
limit: Annotated[int, Query(ge=1, le=100)] = 10,
):
rows = newest_first()
return {"items": rows[offset:offset + limit], "total": len(rows), "offset": offset, "limit": limit}
@router.get("/feed", response_model=CursorPage)
def feed(cursor: str | None = None, limit: Annotated[int, Query(ge=1, le=100)] = 10):
last_id = decode_cursor(cursor) if cursor else None
rows = [row for row in newest_first() if last_id is None or row["id"] < last_id]
page = rows[:limit]
has_more = len(rows) > limit
return {"items": page, "next_cursor": encode_cursor(page[-1]["id"]) if has_more else None}
@router.post("/items", status_code=201, response_model=Item)
def create_item(body: NewItem):
item = {"id": max(row["id"] for row in ITEMS) + 1, "title": body.title}
ITEMS.append(item)
return item# file: main.py
from fastapi import FastAPI
import items
app = FastAPI(title="Robust API demo", version="1.0.0")
app.include_router(items.router)
@app.get("/health")
def health():
return {"status": "ok"}Start it in the background and wait until it answers. The pid goes into a file so you can stop the server later.
uv run fastapi run main.py --port 8000 > server.log 2>&1 &
echo $! > server.pid
curl -s --retry 20 --retry-connrefused --retry-delay 0 http://localhost:8000/health{"status":"ok"}Read the first page of each style, then ask for the second page of the offset list. The second request is the one that goes wrong in real life:
import requests
APP = "http://localhost:8000"
PRACTICE = "http://localhost:8800"
first = requests.get(f"{APP}/items", params={"offset": 0, "limit": 5}).json()
print("offset page 1:", [item["id"] for item in first["items"]], "total", first["total"])
feed_first = requests.get(f"{APP}/feed", params={"limit": 5}).json()
print("cursor page 1:", [item["id"] for item in feed_first["items"]])
print("next_cursor:", feed_first["next_cursor"])offset page 1: [25, 24, 23, 22, 21] total 25
cursor page 1: [25, 24, 23, 22, 21]
next_cursor: eyJsYXN0X2lkIjogMjF9Now simulate a busy product: before the reader asks for page 2, somebody adds a new note at the top of the list. The offset client asks for rows 5 to 9 of a list that has just shifted by one, and gets a row it already saw. The cursor client asks for "everything older than id 21" and is unaffected:
requests.post(f"{APP}/items", json={"title": "Note 26, added while you were reading"})
second_offset = requests.get(f"{APP}/items", params={"offset": 5, "limit": 5}).json()
print("offset page 2:", [item["id"] for item in second_offset["items"]])
second_cursor = requests.get(f"{APP}/feed", params={"limit": 5, "cursor": feed_first["next_cursor"]}).json()
print("cursor page 2:", [item["id"] for item in second_cursor["items"]])offset page 2: [21, 20, 19, 18, 17]
cursor page 2: [20, 19, 18, 17, 16]The offset reader saw note 21 twice. With deletions the opposite happens and a row is skipped silently. For a user scrolling a list that is a glitch; for an AI pipeline that downloads every record to build a training set or an index, it is silent data loss or duplication. The same query in SQL shows why the cursor also wins on cost:
-- offset: the database reads and throws away 100000 rows first
SELECT id, title FROM items ORDER BY id DESC LIMIT 10 OFFSET 100000;
-- cursor ("keyset"): jump straight to the place in the index
SELECT id, title FROM items WHERE id < :last_id ORDER BY id DESC LIMIT 11; -- 11 = limit + 1Fetching limit + 1 rows is the trick used in the endpoint above: if the extra row exists, there is a next page, and no separate count query is needed. Rules for good cursors:
- Sort by a unique, stable key. If you sort by
created_at, which can repeat, include the id as a tiebreaker and put both in the cursor. - Always return
next_cursor: nullon the last page so clients know when to stop. - Cap
limit(here at 100) so one request cannot ask for the whole table. - A base64 cursor is not secret and can be edited by the client. Validate it (the endpoint answers
400) and never put anything in it that grants access; sign it with an HMAC if tampering matters.
The client that crawls everything is a short loop, and it never needs to know what is inside the cursor:
def iter_feed(base_url, limit=10):
cursor = None
while True:
params = {"limit": limit}
if cursor:
params["cursor"] = cursor
page = requests.get(f"{base_url}/feed", params=params, timeout=5).json()
yield from page["items"]
cursor = page["next_cursor"]
if cursor is None:
return
ids = [item["id"] for item in iter_feed(APP, limit=10)]
print(len(ids), ids[:3], ids[-1], len(set(ids)) == len(ids))26 [26, 25, 24] 1 TruePages 1 and 2 of the practice API's own /v1/courses use the offset style (page, per_page, next_page) because that list is small and fixed. Big, changing collections (events, messages, embeddings, log lines) should be cursor-based.
Rate limits and quotas
Every serious API limits its callers, to protect itself from overload, to share capacity fairly, and to control cost. Two ideas are easy to confuse:
| Rate limit | Quota | |
|---|---|---|
| Question it answers | "how fast?" | "how much in total?" |
| Window | seconds or minutes | day or month |
| Typical response when exceeded | 429 Too Many Requests and Retry-After: try again soon | 429 or 403 with an error code like quota_exceeded: retrying will not help until the period resets or the plan changes |
| AI example | 60 requests per minute, 100,000 tokens per minute | 5 million tokens per month, a spending cap |
LLM providers usually limit requests and tokens per minute, per model, per account, so a single huge prompt can trip the limit that thousands of small ones do not. The practice API has a small, fast limit you can hit on purpose: 3 requests per 10 seconds per X-Client-Id. Watch what the fourth request looks like:
for number in range(1, 5):
response = requests.get(f"{PRACTICE}/v1/limited", headers={"X-Client-Id": "robust-demo"})
print(number, response.status_code, response.json(), "Retry-After:", response.headers.get("Retry-After"))1 200 {'ok': True, 'remaining': 2} Retry-After: None
2 200 {'ok': True, 'remaining': 1} Retry-After: None
3 200 {'ok': True, 'remaining': 0} Retry-After: None
4 429 {'detail': 'Too many requests'} Retry-After: 10Three things to read in that answer. The status is 429, which means "you, slow down", not 503, which means "I am broken". The body explains in text. And Retry-After: 10 is the server telling you exactly how long to wait: the standard allows either a number of seconds or an HTTP date, and a good client honours it before trusting its own guess. Many APIs also send informal headers such as X-RateLimit-Remaining and X-RateLimit-Reset on every response (an IETF draft proposes standard RateLimit headers, but the X- names are still the ones you will meet); a client that watches "remaining" can slow down before it is ever blocked. Building a limiter on your own server (fixed window, sliding window, token bucket) is the job of Caching, Rate Limiting and Reliability with Redis.
Retries: exponential backoff, jitter and budgets
Networks fail in short bursts. A retry fixes most of those failures, and a careless retry turns a 30-second hiccup at a provider into an hour-long outage, because thousands of clients all retry at the same moment. A good retry policy has five parts.
- Retry only what is transient: connection errors, timeouts,
429,500,502,503,504. Never retry400,401,403,404or422: the answer will not change. - Retry only what is safe:
GET,PUT,DELETEare idempotent. APOSTis retried only if it carries an idempotency key (next section). - Back off exponentially: wait 0.5 s, 1 s, 2 s, 4 s… up to a cap, so a struggling server gets room to recover.
- Add jitter: pick a random wait between 0 and the backoff value ("full jitter"), so clients spread out instead of arriving in waves.
- Cap the total: a maximum number of attempts, and a retry budget that limits retries across all calls, for example "retries may add at most 10% extra load".
First the schedule itself. Without jitter the waits are exact; with jitter each one is a random number up to that ceiling (a seeded generator makes the numbers repeatable here):
import random
import time
def backoff_ceiling(attempt, base=0.5, cap=8.0):
return min(cap, base * 2 ** attempt)
def backoff_delay(attempt, base=0.5, cap=8.0, rng=random):
return rng.uniform(0, backoff_ceiling(attempt, base, cap))
print("ceilings:", [backoff_ceiling(a) for a in range(7)])
seeded = random.Random(7)
print("full jitter:", [round(backoff_delay(a, rng=seeded), 2) for a in range(7)])ceilings: [0.5, 1.0, 2.0, 4.0, 8.0, 8.0, 8.0]
full jitter: [0.16, 0.15, 1.3, 0.29, 4.29, 2.93, 0.46]Now the retry budget and the client. The budget is a small token bucket: every first attempt deposits a fraction of a token, every retry costs one whole token. When the service is healthy retries are rare and the budget stays full; when everything is failing, the budget runs dry after a few retries and the client stops adding load. Arguments sleep and rng can be replaced, which keeps the function testable and lets this page run without really waiting.
RETRY_STATUS = {429, 500, 502, 503, 504}
IDEMPOTENT_METHODS = {"GET", "HEAD", "PUT", "DELETE", "OPTIONS"}
class RetryBudget:
def __init__(self, ratio=0.1, reserve=2):
self.ratio, self.cap, self.tokens = ratio, float(reserve), float(reserve)
def deposit(self):
self.tokens = min(self.cap, self.tokens + self.ratio)
def withdraw(self):
if self.tokens >= 1:
self.tokens -= 1
return True
return False
def call_with_retries(session, method, url, *, max_attempts=4, base=0.5, cap=8.0,
budget=None, sleep=time.sleep, rng=random, waits=None, **kwargs):
kwargs.setdefault("timeout", (3, 10))
safe = method.upper() in IDEMPOTENT_METHODS or "Idempotency-Key" in kwargs.get("headers", {})
if not safe:
max_attempts = 1
if budget is not None:
budget.deposit()
for attempt in range(max_attempts):
try:
response, error = session.request(method, url, **kwargs), None
if response.status_code not in RETRY_STATUS:
return response
except (requests.ConnectionError, requests.Timeout) as exc:
response, error = None, exc
if attempt == max_attempts - 1 or (budget is not None and not budget.withdraw()):
if error is not None:
raise error
return response
delay = backoff_delay(attempt, base, cap, rng)
if response is not None and "Retry-After" in response.headers:
delay = max(delay, float(response.headers["Retry-After"]))
if waits is not None:
waits.append(round(delay, 2))
sleep(delay)Call the practice API's flaky endpoint, which answers 503 twice for a given key and then succeeds. Instead of sleeping, record the waits:
session = requests.Session()
waits = []
response = call_with_retries(
session, "GET", f"{PRACTICE}/v1/flaky", params={"key": "robust-1", "fail_times": 2},
sleep=lambda seconds: None, rng=random.Random(7), waits=waits,
)
print(response.status_code, response.json())
print("would have waited:", waits)200 {'ok': True, 'attempt': 3}
would have waited: [0.16, 0.15]It took three attempts ("attempt": 3 in the body), and the two waits stayed under their ceilings of 0.5 s and 1 s. Now the rate-limited endpoint. The client id robust-demo is already over its limit from the last section, so every answer is a 429 with Retry-After, and the client waits at least that long, whatever the random jitter says:
waits = []
response = call_with_retries(
session, "GET", f"{PRACTICE}/v1/limited", headers={"X-Client-Id": "robust-demo"},
max_attempts=3, sleep=lambda seconds: None, rng=random.Random(7), waits=waits,
)
print(response.status_code, "after waits", waits)429 after waits [10.0, 10.0]Finally the budget. The endpoint /v1/status/503 always fails. Twenty calls with up to four attempts each could make 60 retries; the budget allows far fewer:
budget = RetryBudget(ratio=0.1, reserve=2)
retries = []
for _ in range(20):
call_with_retries(session, "GET", f"{PRACTICE}/v1/status/503", max_attempts=4,
budget=budget, sleep=lambda seconds: None, waits=retries)
print("calls: 20, retries actually made:", len(retries), "(without a budget: 60)")calls: 20, retries actually made: 3 (without a budget: 60)Libraries do this for you: urllib3.util.Retry with requests adapters, tenacity, and the retry options of the OpenAI and Anthropic SDKs (max_retries). Knowing the policy matters because the defaults are not always right for you: for example, a provider SDK retrying 2 times inside your own retry loop of 3 makes 9 attempts. The next-but-one page builds the same policy for httpx and asyncio: Professional API Clients with httpx and asyncio.
Idempotency keys
You send POST /payments. The server charges the card. The response is lost on the way back and your client times out. If it sends the request again, the customer may be charged twice; if it does not, they may not be charged at all. The client cannot tell which. An idempotency key solves this: the client invents a unique key (a UUID) for the operation and sends it in an Idempotency-Key header on every attempt. The server remembers the first result under that key and replays it for repeats. Stripe popularised the pattern, and an IETF draft describes the header. The same idea protects AI backends: "start this expensive fine-tuning job", "send this email", "debit 3 credits for this generation".
The rules the server follows:
- No key on an unsafe request that needs one:
400. - First time we see a key: do the work, store the result and a fingerprint of the request body.
- Same key, same body: do not repeat the work, return the stored result (mark it, for example with a header).
- Same key, different body: the client has a bug; answer
422instead of guessing. - Keys expire (24 hours is common), and two requests with the same key arriving at the same moment must not both run.
# file: payments.py
import hashlib
import json
import threading
from typing import Annotated
from fastapi import APIRouter, Header, HTTPException, Response
from pydantic import BaseModel, Field
router = APIRouter()
PAYMENTS: list[dict] = []
SEEN: dict[str, dict] = {}
LOCK = threading.Lock()
class PaymentIn(BaseModel):
amount: int = Field(gt=0, description="Amount in poisha")
currency: str = "BDT"
note: str = ""
def fingerprint(payment: PaymentIn) -> str:
return hashlib.sha256(json.dumps(payment.model_dump(), sort_keys=True).encode()).hexdigest()
@router.post("/payments", status_code=201)
def create_payment(
payment: PaymentIn,
response: Response,
idempotency_key: Annotated[str | None, Header()] = None,
):
if not idempotency_key:
raise HTTPException(400, "The Idempotency-Key header is required")
digest = fingerprint(payment)
with LOCK:
saved = SEEN.get(idempotency_key)
if saved is not None:
if saved["fingerprint"] != digest:
raise HTTPException(422, "This Idempotency-Key was already used with a different request")
response.headers["Idempotent-Replayed"] = "true"
return saved["body"]
body = {"id": f"pay_{len(PAYMENTS) + 1:04d}", **payment.model_dump()}
PAYMENTS.append(body)
SEEN[idempotency_key] = {"fingerprint": digest, "body": body}
return body
@router.get("/payments")
def list_payments():
return {"count": len(PAYMENTS), "payments": PAYMENTS}The lock makes "look up the key, then do the work" one step, so two simultaneous requests with one key run one after the other and the second sees the first one's result. That works inside a single process. With several workers or servers, the store must be shared and the claim atomic, for example a database table with a unique constraint on the key (INSERT … ON CONFLICT DO NOTHING) or Redis SET key value NX EX 86400. The two routers that follow (jobs and versions) and a new main.py that mounts all of them come next; save them, then restart the server.
Long-running jobs: 202, a status URL and polling
An HTTP request should answer in seconds. Embedding a thousand documents, rendering a report or running a batch prediction takes minutes. Holding the connection open invites timeouts at every proxy between the client and your server, and a retry would start the job twice. The pattern is:
POST /jobs client asks for the work
<- 202 Accepted "I took it, it is not done"
Location: /jobs/job_001 where to look
Retry-After: 1 how soon to look
GET /jobs/job_001 client polls
<- 200 {"status": "running", "progress": 0.5}
GET /jobs/job_001
<- 200 {"status": "succeeded", "result": {...}}This server fakes the work with a short sleep per document. In production the work runs in a queue worker (the page Dependencies, Lifespan, Middleware and Settings shows why FastAPI background tasks are not enough); the HTTP contract stays the same.
# file: jobs.py
import asyncio
import itertools
from fastapi import APIRouter, HTTPException, Response
from pydantic import BaseModel, Field
router = APIRouter()
JOBS: dict[str, dict] = {}
TASKS: set[asyncio.Task] = set()
COUNTER = itertools.count(1)
class JobIn(BaseModel):
documents: list[str] = Field(min_length=1, max_length=100)
async def run_job(job_id: str, documents: list[str]):
job = JOBS[job_id]
job["status"] = "running"
for number in range(1, len(documents) + 1):
await asyncio.sleep(0.05)
job["progress"] = round(number / len(documents), 2)
job["status"] = "succeeded"
job["result"] = {"embedded": len(documents), "dimensions": 8}
@router.post("/jobs", status_code=202)
async def create_job(body: JobIn, response: Response):
job_id = f"job_{next(COUNTER):03d}"
JOBS[job_id] = {"id": job_id, "status": "queued", "progress": 0.0, "result": None}
task = asyncio.create_task(run_job(job_id, body.documents))
TASKS.add(task)
task.add_done_callback(TASKS.discard)
response.headers["Location"] = f"/jobs/{job_id}"
response.headers["Retry-After"] = "1"
return dict(JOBS[job_id])
@router.get("/jobs/{job_id}")
def get_job(job_id: str):
job = JOBS.get(job_id)
if job is None:
raise HTTPException(404, f"Job {job_id} not found")
return jobKeeping a reference to the task (the TASKS set) matters: Python only holds a weak reference to a running task, so an unreferenced one can be garbage-collected halfway.
Versioning
You will change your API; clients will not change at the same moment. Versioning is how both sides survive that. The first rule is to avoid needing it: adding things (a new optional field, a new endpoint) is safe, so evolve additively for as long as you can. When a change really breaks the old contract, publish it side by side:
| Strategy | Example | Notes |
|---|---|---|
| URL path | /v1/profile, /v2/profile | Most common, visible, easy to route, cache and log. Best default. |
| Header | Accept: application/vnd.example.v2+json | Clean URLs; harder to try in a browser and to cache correctly (Vary: Accept). |
| Query parameter | /profile?version=2 | Simple, but easy to forget and awkward to document. |
| Date-based | Stripe-Version: 2026-03-25 | Each account is pinned to the date it signed up; upgrades are explicit. Great, but needs a lot of server machinery. |
Retire an old version politely: announce it, send Deprecation and Sunset headers on every answer from it, point at the successor with a Link header, and watch the logs to see who still calls it. Two routers do it in FastAPI:
# file: versions.py
from fastapi import APIRouter, Depends, Response
DEPRECATION = "@1767225600"
SUNSET = "Thu, 31 Dec 2026 23:59:59 GMT"
def mark_deprecated(response: Response):
response.headers["Deprecation"] = DEPRECATION
response.headers["Sunset"] = SUNSET
response.headers["Link"] = '</v2/profile>; rel="successor-version"'
v1 = APIRouter(prefix="/v1", dependencies=[Depends(mark_deprecated)])
v2 = APIRouter(prefix="/v2")
@v1.get("/profile")
def profile_v1():
return {"id": 1, "name": "Nadia Rahman"}
@v2.get("/profile")
def profile_v2():
return {"id": 1, "first_name": "Nadia", "last_name": "Rahman"}Now the final main.py. It overwrites the first one and mounts every router:
# file: main.py
from fastapi import FastAPI
import items
import jobs
import payments
import versions
app = FastAPI(title="Robust API demo", version="1.1.0")
app.include_router(items.router)
app.include_router(payments.router)
app.include_router(jobs.router)
app.include_router(versions.v1)
app.include_router(versions.v2)
@app.get("/health")
def health():
return {"status": "ok"}Stop the old server, wait until the port is free, and start the new one:
kill $(cat server.pid)
while curl -s -o /dev/null http://localhost:8000/health; do sleep 0.1; done
uv run fastapi run main.py --port 8000 > server.log 2>&1 &
echo $! > server.pid
curl -s --retry 20 --retry-connrefused --retry-delay 0 http://localhost:8000/health{"status":"ok"}The restart emptied the in-memory data, which is why the examples above ran against the first server. First versions: the old route still works and says it is going away; the new one is clean:
curl -s -i http://localhost:8000/v1/profile | tr -d "\r" | grep -i -E "^(HTTP|deprecation|sunset|link|\{)"
echo
curl -s http://localhost:8000/v2/profileHTTP/1.1 200 OK
deprecation: @1767225600
sunset: Thu, 31 Dec 2026 23:59:59 GMT
link: </v2/profile>; rel="successor-version"
{"id":1,"name":"Nadia Rahman"}
{"id":1,"first_name":"Nadia","last_name":"Rahman"}Now idempotency. The client picks a key per operation, and its retry sends the same key. The server creates one payment, not two, and says that the second answer was a replay. Reusing the key for a different amount is refused:
import uuid
key = "order-1001" # in real code: str(uuid.uuid4()), created once per operation
body = {"amount": 25000, "note": "Course fee"}
first = requests.post(f"{APP}/payments", json=body, headers={"Idempotency-Key": key})
retry = requests.post(f"{APP}/payments", json=body, headers={"Idempotency-Key": key})
print(first.status_code, first.json()["id"], first.headers.get("Idempotent-Replayed"))
print(retry.status_code, retry.json()["id"], retry.headers.get("Idempotent-Replayed"))
changed = requests.post(f"{APP}/payments", json={**body, "amount": 99999}, headers={"Idempotency-Key": key})
print(changed.status_code, changed.json()["detail"])
missing = requests.post(f"{APP}/payments", json=body)
print(missing.status_code, missing.json()["detail"])
print("payments stored:", requests.get(f"{APP}/payments").json()["count"])201 pay_0001 None
201 pay_0001 true
422 This Idempotency-Key was already used with a different request
400 The Idempotency-Key header is required
payments stored: 1This is also why the call_with_retries function above refuses to retry a POST unless it carries the header. With the key, retrying is safe, and the client can use the full backoff policy:
response = call_with_retries(
requests, "POST", f"{APP}/payments", json=body, headers={"Idempotency-Key": key},
sleep=lambda seconds: None,
)
print(response.status_code, response.json()["id"], response.headers.get("Idempotent-Replayed"))201 pay_0001 trueNow the job. The POST returns at once with 202, a Location and a status of queued. The client then polls the status URL until the job is finished, with a pause between polls and an overall timeout, because a poll loop without a deadline is a bug waiting for the day the job never ends:
created = requests.post(f"{APP}/jobs", json={"documents": ["a", "b", "c", "d"]})
print(created.status_code, created.headers["Location"], created.headers["Retry-After"])
print(created.json())
def wait_for_job(base_url, location, interval=0.1, timeout=5.0):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
job = requests.get(base_url + location, timeout=5).json()
if job["status"] in ("succeeded", "failed"):
return job
time.sleep(interval)
raise TimeoutError(f"{location} did not finish in {timeout} seconds")
print(wait_for_job(APP, created.headers["Location"]))
print(requests.get(f"{APP}/jobs/job_999").status_code)202 /jobs/job_001 1
{'id': 'job_001', 'status': 'queued', 'progress': 0.0, 'result': None}
{'id': 'job_001', 'status': 'succeeded', 'progress': 1.0, 'result': {'embedded': 4, 'dimensions': 8}}
404Real services add a few touches to this pattern: the client may also send an Idempotency-Key so a retried POST /jobs does not start a second job; a DELETE /jobs/{id} can cancel; on success the status resource can link to the result, or answer 303 See Other pointing at it; and instead of polling, the server can call the client back with a webhook, the topic of the next page.
OpenAPI contracts and compatibility
FastAPI writes an OpenAPI document for your app, a machine-readable contract listing every path, method, parameter and response shape. It is served at /openapi.json and drives /docs. Read it as data:
spec = requests.get(f"{APP}/openapi.json").json()
print(spec["openapi"], spec["info"]["title"], spec["info"]["version"])
for path, methods in spec["paths"].items():
print(f"{path:<18}", sorted(method.upper() for method in methods))
print(sorted(spec["components"]["schemas"]["Item"]["properties"]))3.1.0 Robust API demo 1.1.0
/items ['GET', 'POST']
/feed ['GET']
/payments ['GET', 'POST']
/jobs ['POST']
/jobs/{job_id} ['GET']
/v1/profile ['GET']
/v2/profile ['GET']
/health ['GET']
['id', 'title']The contract is the promise to your clients, so changes to it are what you review, not just the code. Some changes are safe; others break somebody:
| Non-breaking (additive) | Breaking |
|---|---|
| A new endpoint | Removing or renaming an endpoint |
| A new optional request parameter or field | A new required parameter or field |
| A new field in a response (clients must ignore unknown fields) | Removing or renaming a response field, or changing its type or meaning |
| A new optional enum value in a response, if clients were told to expect more | Narrowing what you accept (a shorter maximum length, a stricter pattern) |
| A new error code only where clients treat unknown codes generically | Changing a status code or error shape clients depend on; changing pagination order |
That table can be checked by a program. This small checker compares two contracts and reports the breaking changes it can see. Real tools do more (the oasdiff command-line tool is a good one), but the idea is exactly this, and it can run in CI on every pull request:
import copy
def operations(spec):
for path, methods in spec["paths"].items():
for method, operation in methods.items():
yield (method.upper(), path), operation
def required_params(operation):
return {p["name"] for p in operation.get("parameters", []) if p.get("required")}
def resolve(spec, schema):
if "$ref" in schema:
return spec["components"]["schemas"][schema["$ref"].split("/")[-1]]
return schema
def field_names(spec, schema, prefix=""):
schema = resolve(spec, schema)
if schema.get("type") == "array":
return field_names(spec, schema["items"], prefix)
names = set()
for name, sub in schema.get("properties", {}).items():
names.add(prefix + name)
names |= field_names(spec, sub, prefix + name + ".")
return names
def response_fields(spec, operation):
for code in ("200", "201", "202"):
if code in operation["responses"]:
content = operation["responses"][code].get("content", {}).get("application/json", {})
return field_names(spec, content.get("schema", {}))
return set()
def breaking_changes(old, new):
problems = []
new_operations = dict(operations(new))
for (method, path), old_operation in operations(old):
label = f"{method} {path}"
new_operation = new_operations.get((method, path))
if new_operation is None:
problems.append(f"{label}: endpoint removed")
continue
for name in sorted(required_params(new_operation) - required_params(old_operation)):
problems.append(f"{label}: new required parameter {name!r}")
for name in sorted(response_fields(old, old_operation) - response_fields(new, new_operation)):
problems.append(f"{label}: response field {name!r} removed")
return problems
print("no change:", breaking_changes(spec, spec))no change: []Now make three breaking changes and one harmless one in a copy of the contract, as if a developer had edited the code, and see what the checker says:
changed = copy.deepcopy(spec)
del changed["paths"]["/feed"] # endpoint removed
changed["paths"]["/items"]["get"]["parameters"].append( # new required parameter
{"name": "tenant", "in": "query", "required": True, "schema": {"type": "string"}})
properties = changed["components"]["schemas"]["Item"]["properties"]
properties["name"] = properties.pop("title") # field renamed
changed["paths"]["/stats"] = {"get": {"responses": {"200": {"description": "ok"}}}} # new endpoint
for problem in breaking_changes(spec, changed):
print(problem)GET /items: new required parameter 'tenant'
GET /items: response field 'items.title' removed
POST /items: response field 'title' removed
GET /feed: endpoint removedThe new /stats endpoint is not reported, because adding it breaks nobody. A contract also lets you generate typed client code and lets consumers write contract tests; the testing page uses a saved snapshot of /openapi.json for exactly this.
Consuming untrusted external APIs
Everything above was about APIs you build. Most AI backends are also clients of APIs they do not control: LLM providers, search, scrapers, partner data, user-supplied webhooks and URLs. Treat every byte from outside your system as untrusted input, even from a company you trust, because bugs, outages and attackers all produce strange answers.
| Risk | Defence |
|---|---|
| It never answers | Connect and read timeouts on every call, plus an overall deadline (a server dripping one byte a second never trips a per-read timeout) |
| It answers with gigabytes | Stream the body and stop at a size limit; check Content-Length early but do not rely on it |
| It sends the wrong shape | Validate with Pydantic: types, ranges, lengths, allowed values; ignore unknown fields; fail loudly on missing ones |
| It redirects you somewhere internal | Do not follow redirects blindly; for user-supplied URLs block private and metadata addresses (SSRF, see API Security and the OWASP API Top 10) |
| Its text carries instructions | Text from a web page or tool result is data, not commands: never run it, put it in SQL or HTML unescaped, or let it override your prompt |
| It changes without warning | Pin versions where you can, log validation failures, and alert when the failure rate rises |
Here is a wrapper that applies the first three defences. It reads the body in chunks and refuses to continue past a limit:
import json
class ResponseTooLarge(Exception):
pass
def fetch_json(method, url, *, max_bytes=100_000, timeout=(3, 5), deadline=10.0, **kwargs):
started = time.monotonic()
with requests.request(method, url, stream=True, timeout=timeout, allow_redirects=False, **kwargs) as response:
response.raise_for_status()
if "application/json" not in response.headers.get("Content-Type", ""):
raise ValueError(f"expected JSON, got {response.headers.get('Content-Type')!r}")
chunks, size = [], 0
for chunk in response.iter_content(chunk_size=1024):
size += len(chunk)
if size > max_bytes:
raise ResponseTooLarge(f"more than {max_bytes} bytes")
if time.monotonic() - started > deadline:
raise TimeoutError(f"took longer than {deadline} seconds")
chunks.append(chunk)
return json.loads(b"".join(chunks))
print(fetch_json("GET", f"{PRACTICE}/v1/courses/8"))
try:
fetch_json("POST", f"{PRACTICE}/v1/echo", json={"blob": "x" * 5000}, max_bytes=1000)
except ResponseTooLarge as exc:
print("ResponseTooLarge:", exc)
try:
fetch_json("GET", f"{PRACTICE}/v1/slow", params={"seconds": 3}, timeout=(1, 0.5))
except requests.exceptions.Timeout as exc:
print("Timeout:", type(exc).__name__){'id': 8, 'title': 'RAG Systems', 'level': 'advanced', 'hours': 10, 'rating': 4.9}
ResponseTooLarge: more than 1000 bytes
Timeout: ReadTimeoutThen validate the shape. A strict model accepts what you expect and nothing else; here it is asked to read the weather response as if it were a course, which is what an upstream API silently changing looks like:
from typing import Literal
from pydantic import BaseModel, ConfigDict, Field, ValidationError
class Course(BaseModel):
model_config = ConfigDict(extra="ignore")
id: int
title: str = Field(max_length=200)
level: Literal["beginner", "intermediate", "advanced"]
hours: int = Field(ge=0, le=1000)
rating: float = Field(ge=0, le=5)
page = fetch_json("GET", f"{PRACTICE}/v1/courses", params={"per_page": 20})
courses = [Course(**row) for row in page["items"]]
print(len(courses), "valid courses, first:", courses[0].title)
try:
Course(**fetch_json("GET", f"{PRACTICE}/v1/weather", params={"city": "Dhaka"}))
except ValidationError as exc:
print("rejected, bad fields:", [error["loc"][0] for error in exc.errors()])10 valid courses, first: How AI Works
rejected, bad fields: ['id', 'title', 'level', 'hours', 'rating']Validation at the boundary means the rest of your program only ever sees clean, typed objects. That is also what stops an upstream surprise from turning into a confusing KeyError three layers deeper.
Real-world use
- Data pipelines that pull from partner APIs use cursor pagination, backoff with jitter and a validation layer, so a nightly sync survives bad minutes without duplicating or dropping rows.
- LLM providers rate-limit by requests and tokens per minute and return
429withRetry-After. SDK retries, a retry budget and queueing in front of the provider keep a burst of users from becoming an outage. - Payment, credit and quota systems use idempotency keys so a retried "debit 3 credits" never debits twice. The same applies to "create fine-tuning job" and "send email".
- Batch inference, embeddings and report generation answer
202with a job URL; the front end shows a progress bar by polling, or receives a webhook. - Public APIs publish versions and deprecation dates, and run an OpenAPI diff in CI so nobody breaks the contract by accident.
Common mistakes
- Offset pagination on a live, large table. Rows repeat or vanish between pages and deep pages get slower and slower. Use a cursor on a unique, indexed sort key, cap
limit, and returnnullat the end. - Retrying without backoff, jitter or a limit. A fixed one-second retry from ten thousand clients is a self-inflicted attack. Back off exponentially, add jitter, honour
Retry-After, and cap attempts and total retries. - Retrying a
POSTthat has no idempotency key. The first attempt may have worked. Add the key, fingerprint the body, and answer422if the key is reused with different data. - Holding the connection open for a long job. Proxies time out and retries start the work twice. Answer
202with aLocation, poll with a deadline, and run the work outside the request. - Trusting the other side. No timeout, no size limit and no validation means one bad response can hang a worker, fill its memory or crash it far from the real cause. Wrap every external call in the same safe fetch-and-validate function.
Try it yourself
- Easy: use
/feedwithlimit=7and follownext_cursoruntil it isnull. Print how many pages you needed and how many items you received in total. - Medium: send two
POST /paymentsrequests with the sameIdempotency-Keybut different amounts, and print both status codes and the error detail. - Medium: start a job for 2 documents and write your own polling loop that waits
0.02s, then doubles the pause after each poll up to0.2s (a backoff for polling), stops when the job is done, and prints the final status and result. - Hard: write
additive_changes(old, new)that lists new endpoints and new response fields between two contracts (the reverse ofbreaking_changes), and run it onspecand the editedchangedcontract from this page.
Answers
# 1. Easy
pages, total, cursor = 0, 0, None
while True:
params = {"limit": 7, **({"cursor": cursor} if cursor else {})}
page = requests.get(f"{APP}/feed", params=params).json()
pages += 1
total += len(page["items"])
cursor = page["next_cursor"]
if cursor is None:
break
print(pages, total)
# 2. Medium
one = requests.post(f"{APP}/payments", json={"amount": 100}, headers={"Idempotency-Key": "ex-2"})
two = requests.post(f"{APP}/payments", json={"amount": 200}, headers={"Idempotency-Key": "ex-2"})
print(one.status_code, one.json()["id"])
print(two.status_code, two.json()["detail"])
# 3. Medium
job = requests.post(f"{APP}/jobs", json={"documents": ["x", "y"]}).json()
interval, polls = 0.02, 0
while True:
job = requests.get(f"{APP}/jobs/{job['id']}").json()
polls += 1
if job["status"] in ("succeeded", "failed"):
break
time.sleep(interval)
interval = min(interval * 2, 0.2)
print(job["status"], job["result"], polls >= 1)
# 4. Hard
def additive_changes(old, new):
found = []
old_operations = dict(operations(old))
for key, operation in operations(new):
if key not in old_operations:
found.append(f"{key[0]} {key[1]}: new endpoint")
else:
for name in sorted(response_fields(new, operation) - response_fields(old, old_operations[key])):
found.append(f"{key[0]} {key[1]}: new response field {name!r}")
return found
for line in additive_changes(spec, changed):
print(line)4 25
201 pay_0002
422 This Idempotency-Key was already used with a different request
succeeded {'embedded': 2, 'dimensions': 8} True
GET /items: new response field 'items.name'
POST /items: new response field 'name'
GET /stats: new endpointStop the server when you are done, so port 8000 is free for the next page:
kill $(cat server.pid)Summary
- Offset pagination is simple but repeats or skips rows when data changes and gets slow when deep; cursor (keyset) pagination on a unique, indexed key is stable and fast. Keep cursors opaque, validate them, cap
limitand end withnext_cursor: null. - Rate limits answer "how fast", quotas "how much". A
429withRetry-Aftertells the client how long to wait. - Retry only transient failures of safe requests, with exponential backoff, full jitter,
Retry-After, a maximum number of attempts and a retry budget. - An
Idempotency-Keymakes aPOSTsafe to retry: store the first result with a fingerprint of the body, replay it for repeats, refuse a changed body with422. For long work, answer202with aLocationstatus URL and poll with a deadline. - Prefer additive change; when you must break, version (URL path is the default) and send
DeprecationandSunsetheaders. The OpenAPI document is your contract and can be diffed in code. Treat external APIs as untrusted: timeouts, size limits, deadlines and Pydantic validation at the boundary.
Next: Webhooks and Streaming with Server-Sent Events turns the direction around: instead of polling a job, the server calls you back with a signed webhook, and instead of waiting for a whole answer, it streams the answer piece by piece.

