12.2. API Reliability and Production Patterns#
API code becomes production code when other code depends on it. Reliability means the client sends data in the format the server expects, keeps secrets out of code, reads nested responses defensively, follows pagination, retries transient failures, and validates responses, instead of assuming every request succeeds and every response has the expected shape.
12.2.1. POST Requests#
A GET request retrieves data. A POST request sends data, often to create a record or submit a form. In requests, use json= when the request body should be JSON. The library serializes the dictionary and sets the appropriate content type.
12.2.1.1. Worked Example: Prepare a JSON POST#
This example prepares a POST request without sending it, so you can inspect what json= does: it sets the Content-Type header to application/json and serializes the dictionary into the request body.
requests.Request() describes the request you intend to make: the method, URL, and any params, headers, or body. Its .prepare() method encodes that description into a PreparedRequest, the exact request that would be sent.
import requests
payload = {"name": "Alice", "role": "student"}
req = requests.Request( # a Request: describes what to send
"POST",
"https://api.example.test/users",
json=payload,
)
print(req.json) # still a Python dict
prepared = req.prepare() # a PreparedRequest: encoded and ready to send
print(prepared.method)
print(prepared.url)
print(prepared.headers["Content-Type"])
print(prepared.body.decode())
{'name': 'Alice', 'role': 'student'}
POST
https://api.example.test/users
application/json
{"name": "Alice", "role": "student"}
The body of a prepared request is stored as bytes, so .decode() turns it back into text for printing.
Use json=, not data=, for a JSON API. Passing a dictionary to data= sends it form-encoded (name=Alice&role=student) with the content type application/x-www-form-urlencoded.
.prepare() is for inspecting a request. To send one, call requests.post() with the same arguments plus a timeout. The host api.example.test is a placeholder, so this snippet is shown rather than run:
response = requests.post(
"https://api.example.test/users",
json=payload,
timeout=10,
)
response.raise_for_status() # a successful create usually returns 201 Created
created = response.json() # the server's copy of the new record
### Exercise: POST Payload
# Prepare a POST request to https://api.example.test/events whose JSON body
# sets "event_type" to "login" and "count" to 3. Print the method and the
# decoded body.
# Print exactly:
# POST
# {"event_type": "login", "count": 3}
### Your code starts here
payload = {}
prepared = requests.Request("POST", "https://api.example.test/events", json=payload).prepare()
print(prepared.method)
print(prepared.body.decode())
### Your code ends here
POST
{}
POST
{"event_type": "login", "count": 3}
12.2.2. Headers and API Keys#
Headers carry request metadata. Authentication tokens often belong in an Authorization header, not in the URL, usually in the form Bearer <token>. Bearer means that whoever holds (bears) the token is treated as authorized, which is why the token must stay secret. Some APIs expect the key in a custom header instead, most commonly X-API-Key; the API’s documentation tells you which header name to use. Keep real secrets out of notebooks and source files: read them from environment variables and fail clearly when they are missing.
12.2.2.1. Worked Example: Build Auth Headers#
This function reads the API key from an environment variable and places it in an Authorization header. If the variable is not set, it falls back to a placeholder so the example still runs.
(.venv) user✪host:~/workspace/py$ env
SHELL=/opt/homebrew/bin/bash
COLORTERM=truecolor
...
...
GEMINI_API_KEY=############################
...
OPENAI_API_KEY=sk-proj-############################-
...
...
import os
def build_headers(token_env_var="DEMO_API_KEY"):
token = os.environ.get(token_env_var)
if token is None:
token = "demo-token" ### fallback
return {
"Authorization": f"Bearer {token}",
"Accept": "application/json",
}
headers = build_headers()
print(headers["Authorization"])
print(headers["Accept"])
Bearer demo-token
application/json
The fallback keeps this example runnable. In real code, replace it with an error so a missing key is caught immediately:
token = os.environ.get("DEMO_API_KEY")
if not token:
raise RuntimeError("Set the DEMO_API_KEY environment variable first")
### Exercise: API Key Header
# Some APIs expect the key in a custom header instead of `Authorization`.
# Complete `build_key_headers()` so it reads the key from the environment
# variable named by `env_var`, uses `fallback` when the variable is not set,
# and returns a dictionary with an `X-API-Key` header and an `Accept` header
# of `application/json`. The test code attaches the headers to a prepared
# GET request.
# Print exactly:
# test-key
# application/json
def build_key_headers(env_var="REPORTS_API_KEY", fallback="test-key"):
### Your code starts here
return {}
### Your code ends here
headers = build_key_headers()
prepared = requests.Request("GET", "https://api.example.test/reports", headers=headers).prepare()
print(prepared.headers.get("X-API-Key"))
print(prepared.headers.get("Accept"))
None
None
test-key
application/json
12.2.3. Nested JSON Parsing#
Many API responses contain dictionaries inside lists inside dictionaries. Direct indexing is concise when the response contract is guaranteed. The .get() method is safer when fields may be optional.
12.2.3.1. Worked Example: Direct and Defensive Access#
The same payload is read in two ways. Direct indexing reaches the user’s name, which the response contract guarantees. The metrics list is optional, so it is read defensively: .get() supplies an empty list when the metrics key is missing, and the conditional returns 0 when the list is empty. Neither case raises a KeyError or an IndexError.
payload = {
"user": {
"id": 101,
"profile": {"name": "Nia", "department": "Analytics"},
},
"metrics": [{"name": "requests", "value": 42}],
}
name = payload["user"]["profile"]["name"]
metrics = payload.get("metrics", [])
first_metric = metrics[0].get("value", 0) if metrics else 0
print(name)
print(first_metric)
Nia
42
.get() protects against a missing key, not against a key whose value is null. With {"user": None}, payload.get("user", {}) returns None, and the next .get() raises AttributeError. When an API can return null for a nested object, write (payload.get("user") or {}).
user = payload.get("user") or {}
profile = user.get("profile") or {}
name = profile.get("name") or "Unknown"
### Exercise: Defensive Parsing
# Write `get_department(payload)` so it returns the nested department value
# when present and 'unknown' otherwise, including when "user" is None.
# Print exactly:
# Analytics
# unknown
# unknown
def get_department(payload):
### Your code starts here
return None
### Your code ends here
print(get_department(payload))
print(get_department({"user": {}}))
print(get_department({"user": None}))
None
None
None
Analytics
unknown
unknown
12.2.4. Pagination Patterns#
APIs often return large result sets in pages. A client should keep requesting pages until the response says there is no next page. Page-based APIs often use an integer page number; cursor-based APIs use a token returned by the previous response. With a cursor, each response includes a value such as next_cursor that you send with the next request, and a missing or None cursor means you have reached the last page.
12.2.4.1. Worked Example: Page-Based Pagination#
A small dictionary stands in for an API that returns one page at a time. fetch_all_pages() keeps requesting the next page and collecting its items until a page reports next_page as None.
pages = {
1: {"items": ["a", "b"], "next_page": 2},
2: {"items": ["c", "d"], "next_page": 3},
3: {"items": ["e"], "next_page": None},
}
def get_page(page_number):
return pages[page_number]
def fetch_all_pages(get_page_fn, first_page=1):
items = []
page = first_page
while page is not None:
payload = get_page_fn(page)
items.extend(payload["items"])
page = payload["next_page"]
return items
print(fetch_all_pages(get_page))
['a', 'b', 'c', 'd', 'e']
### Exercise: Cursor-Based Pagination
# `cursor_pages` stands in for a cursor-based API. Each response holds a
# `results` list and a `next_cursor` token that names the next page; the
# last page sets `next_cursor` to None. Complete `fetch_all_cursor(get_fn)`
# so it starts at the cursor "start", follows each `next_cursor` token, and
# returns every result in order.
# Print exactly:
# [101, 102, 103, 104, 105]
cursor_pages = {
"start": {"results": [101, 102], "next_cursor": "k7"},
"k7": {"results": [103, 104], "next_cursor": "m2"},
"m2": {"results": [105], "next_cursor": None},
}
def get_by_cursor(cursor):
return cursor_pages[cursor]
def fetch_all_cursor(get_fn, first_cursor="start"):
results = []
### Your code starts here
### Your code ends here
return results
print(fetch_all_cursor(get_by_cursor))
[]
[101, 102, 103, 104, 105]
12.2.5. Retry with Exponential Backoff#
Retries help with transient failures: timeouts, rate limits, and temporary server errors. A rate-limited request returns 429 Too Many Requests, often with a Retry-After header that says how long to wait (usually a number of seconds). When the header is present, wait that long instead of using your own backoff delay. Exponential backoff increases the delay after each failed attempt. In production, add jitter so many clients do not retry at exactly the same time. The examples below leave jitter out so their output is the same on every run. Adding it takes one change, plus import random: delay = base_delay * 2 ** (attempt - 1) * random.uniform(0.5, 1.5).
12.2.5.1. Worked Example: Retry a Flaky Function#
FlakySource raises a timeout a set number of times before it succeeds, which mimics a temporary network problem. retry_call() tries again after each failure, doubling the wait each time, and re-raises the error if the last attempt also fails.
import time
import requests
class FlakySource:
def __init__(self, failures_before_success):
self.failures_before_success = failures_before_success
self.calls = 0
def get(self):
self.calls += 1
if self.calls <= self.failures_before_success:
raise requests.Timeout("temporary timeout")
return {"status": "ok", "calls": self.calls}
def retry_call(call_fn, retries=3, base_delay=0.01):
for attempt in range(1, retries + 1):
try:
return call_fn()
except requests.Timeout:
if attempt == retries:
raise
delay = base_delay * (2 ** (attempt - 1))
time.sleep(delay)
source = FlakySource(failures_before_success=2)
print(retry_call(source.get, retries=4))
{'status': 'ok', 'calls': 3}
retry_call() retries whatever function it is given; it cannot tell a GET from a POST. Deciding whether a call is safe to repeat is the caller’s job, and the next subsection gives the rule.
12.2.5.2. Which Requests Are Safe to Retry#
A timeout does not tell you whether the server received the request. If it did, a retry sends the same request a second time. That is harmless for an idempotent method such as GET, PUT, or DELETE, because repeating it leaves the server in the same state (see the methods table in 12.1 API Basics). Repeating a POST can create a second order or charge a card twice. A careful client therefore retries automatically only when two conditions hold: the method is idempotent, and the failure is transient, such as a timeout or a 5xx status.
Two details from the method table in the previous section matter once your code retries requests:
PATCH is idempotent only sometimes. The HTTP standard does not require it, so it depends on the body. Setting a field to a fixed value, such as
{"units": "celsius"}, leaves the record the same however many times you send it. A PATCH that increments a counter or appends to a list changes the record again each time.PUT replaces the whole record. It is safe to repeat, but any field you leave out may be erased, while PATCH sends only the fields that change.
APIs that must accept retried POST requests often let the client send an Idempotency-Key header with a unique value. The server remembers the key and ignores a second request that carries it.
IDEMPOTENT_METHODS = {"GET", "PUT", "DELETE"}
def should_retry(method, status_code):
"""Retry only idempotent requests that failed with a server error."""
return method.upper() in IDEMPOTENT_METHODS and status_code >= 500
for method, status in [("GET", 503), ("PUT", 500), ("POST", 503), ("GET", 404)]:
print(f"{method} {status}: retry={should_retry(method, status)}")
GET 503: retry=True
PUT 500: retry=True
POST 503: retry=False
GET 404: retry=False
should_retry() covers the status-code half of the rule. The timeout half is handled the way retry_call() does it, by catching requests.Timeout, and the same method check applies there. A 429 response is a separate case: wait for Retry-After, then try again. Treating every 5xx status as temporary is also a simplification: 501 Not Implemented, for example, fails the same way every time.
### Exercise: Retry on Server Errors
# A 5xx status code usually means the server had a temporary problem, so a
# GET request like this one is worth retrying. `make_fake_call()` returns a
# stand-in function that replies with the given status codes in order. Complete
# `retry_on_server_error(call_fn)` so it calls `call_fn()`, retries with
# exponential backoff while the status is 500 or higher, and returns a tuple
# of the final response and the list of delays it waited. After `retries`
# attempts, return the last response even if it is still an error.
# Print exactly:
# ({'status': 200}, [0.001, 0.002])
# ({'status': 404}, [])
# ({'status': 503}, [0.001, 0.002, 0.004])
def make_fake_call(statuses):
replies = iter(statuses)
def call():
return {"status": next(replies)}
return call
def retry_on_server_error(call_fn, retries=4, base_delay=0.001):
delays = []
### Your code starts here
response = call_fn()
### Your code ends here
return response, delays
print(retry_on_server_error(make_fake_call([503, 500, 200])))
print(retry_on_server_error(make_fake_call([404])))
print(retry_on_server_error(make_fake_call([503, 503, 503, 503])))
({'status': 503}, [])
({'status': 404}, [])
({'status': 503}, [])
({'status': 200}, [0.001, 0.002])
({'status': 404}, [])
({'status': 503}, [0.001, 0.002, 0.004])
12.2.6. Response Contract Validation#
A response contract defines the keys and value types your code expects. Validate close to the API boundary so downstream analysis code receives clean, predictable data.
12.2.6.1. Worked Example: Validate Required Keys#
parse_weather_response() checks the response before using it. It raises a ValueError that names exactly which fields are missing, so a bad response fails at the API boundary with a clear message instead of deep inside later analysis code. The second call passes a payload without windspeed and shows the message the caller receives.
def parse_weather_response(payload):
if "current_weather" not in payload:
raise ValueError("Missing current_weather in API response")
current = payload["current_weather"]
required = ["temperature", "windspeed"]
missing = [key for key in required if key not in current]
if missing:
raise ValueError(f"Missing weather fields: {missing}")
return {
"temperature": current["temperature"],
"windspeed": current["windspeed"],
}
print(parse_weather_response({"current_weather": {"temperature": 21.4, "windspeed": 13.2}}))
try:
parse_weather_response({"current_weather": {"temperature": 21.4}})
except ValueError as error:
print("Rejected:", error)
{'temperature': 21.4, 'windspeed': 13.2}
Rejected: Missing weather fields: ['windspeed']
This example checks only that the keys are present. A stricter contract also checks types, as the final exercise does with isinstance().
### Exercise: Validate a User Record
# Write `parse_user(payload)`. It checks for the keys "id", "name", and
# "email". If any are missing, it raises ValueError with the message
# "Missing user fields: [...]", listing the missing keys in that order.
# Otherwise it returns a new dict with only those three keys.
# Call it on `good_user`, then on `bad_user` inside try/except, and print
# "Rejected:" with the error message for the failure.
# Print exactly:
# {'id': 7, 'name': 'Ana', 'email': 'ana@example.test'}
# Rejected: Missing user fields: ['email']
good_user = {"id": 7, "name": "Ana", "email": "ana@example.test", "plan": "free"}
bad_user = {"id": 8, "name": "Ben"}
### Your code starts here
### Your code ends here
{'id': 7, 'name': 'Ana', 'email': 'ana@example.test'}
Rejected: Missing user fields: ['email']
12.2.7. Exercises#
This task combines pagination and response contract validation from this section.
### Exercise: Resilient Client
# `get_page` returns the pages of a page-based API, and `get_broken_page`
# returns the same pages except that page 2 has no "items" list.
# Complete `fetch_valid_pages(get_page_fn)` so it fetches every page,
# starting at page 1, and validates each page before using it. Raise
# ValueError with "Page <n> has no items list" when "items" is missing or is
# not a list, and "Page <n> has no next_page key" when "next_page" is missing.
# Call it on `get_page`, then on `get_broken_page` inside try/except, and
# print "Rejected:" with the error message for the failure.
# Print exactly:
# ['a', 'b', 'c', 'd', 'e']
# Rejected: Page 2 has no items list
pages = {
1: {"items": ["a", "b"], "next_page": 2},
2: {"items": ["c", "d"], "next_page": 3},
3: {"items": ["e"], "next_page": None},
}
broken_pages = {**pages, 2: {"next_page": 3}}
def get_page(page_number):
return pages[page_number]
def get_broken_page(page_number):
return broken_pages[page_number]
def fetch_valid_pages(get_page_fn):
items = []
page = 1
while page is not None:
payload = get_page_fn(page)
### Your code starts here
page = None
### Your code ends here
return items
print(fetch_valid_pages(get_page))
try:
fetch_valid_pages(get_broken_page)
except ValueError as error:
print("Rejected:", error)
[]
['a', 'b', 'c', 'd', 'e']
Rejected: Page 2 has no items list