1. HTTP, REST APIs & External Services
Calling External APIs Safely: httpx, Timeouts, Retries & Pagination
Consume third-party REST APIs reliably in Python using httpx, mandatory timeouts, bearer headers, exponential backoff retries, and paginated loops.
- Send GET and POST requests with query params, Bearer headers, and mandatory timeouts
- Handle HTTP 4xx/5xx failures cleanly with raise_for_status() and retries
- Fetch multi-page API results cleanly using pagination loops
Before building your own backend APIs, you will frequently consume other APIs—Stripe payments, GitHub webhooks, OpenAI/Gemini endpoints, or internal microservices.
In modern Python, httpx is the standard HTTP client. Unlike the older requests library, httpx supports both synchronous (Client) and asynchronous (AsyncClient) code, HTTP/2, connection pooling, and strict timeout defaults.
1. Outbound APIs in Backend Architecture
When your FastAPI backend calls an external service inside a request handler:
User Request ─▶ Your FastAPI Endpoint ─▶ httpx Client ─▶ External API (Stripe / GitHub)
│
Always enforce timeout + raise_for_status()If that third-party API slows down from 80 ms to 30 s and you have no timeout or retry strategy, your backend workers stall and your entire site goes down with it.
2. Never Make an HTTP Call Without a timeout
If an external server hangs and you omit timeout=, your Python worker can freeze indefinitely waiting on a silent TCP socket.
import os
import httpx
API_TOKEN = os.environ.get("GITHUB_TOKEN", "")
# Granular timeouts prevent stalling on slow DNS, TLS, or body reads
timeout = httpx.Timeout(connect=2.0, read=5.0, write=5.0, pool=2.0)
with httpx.Client(
base_url="https://api.github.com",
headers={"Authorization": f"Bearer {API_TOKEN}", "Accept": "application/json"},
timeout=timeout,
) as client:
response = client.get("/users/octocat", params={"per_page": 10})
response.raise_for_status() # Raises httpx.HTTPStatusError on 4xx/5xx!
data = response.json()
print(data["login"])Using with httpx.Client(...) reuses underlying TCP/TLS connections (connection pooling), avoiding a fresh TLS handshake on every call. In async FastAPI routes (async def), swap to async with httpx.AsyncClient(...) as client: and await client.get(...) so you never block the event loop.
httpx and requests do not raise an exception on 404 or 500 responses by default! Calling response.raise_for_status() catches HTTP errors immediately instead of crashing later with KeyError on an error JSON payload.
3. Retrying Transient Failures with Exponential Backoff (+ Jitter)
wait ~0.5s
wait ~1.0s + jitter
Recovered!
Retry transient 429/502/503 responses with increasing delays; fail immediately on client bugs like 400 or 401.
Networks hiccup (502 Bad Gateway, 503 Service Unavailable, 504 Gateway Timeout, 429 Too Many Requests). A resilient client distinguishes transient errors from permanent bugs:
| Status / Error | Safe to Retry? | Why |
|---|---|---|
ConnectTimeout / 502 / 503 / 504 | Yes (on idempotent GET/PUT) | Temporary network or upstream overload |
429 Too Many Requests | Yes (respect Retry-After header) | Rate limit window resets shortly |
400 / 401 / 403 / 404 / 422 | No | Your payload, token, or URL is wrong; retrying wastes quota |
POST /payments (unknown timeout) | Only with Idempotency-Key | Blind retries can double-charge customers! |
When retrying, multiply the wait time (exponential backoff: 0.5s, 1.0s, 2.0s) and add small random jitter (random.uniform(0, 0.2)) so thousands of clients don't slam the recovering server at the exact same millisecond:
import random
import time
RETRYABLE_STATUSES = {429, 502, 503, 504}
def call_with_retry(fetch_fn, max_attempts: int = 3, base_delay: float = 0.5):
for attempt in range(1, max_attempts + 1):
try:
return fetch_fn()
except RuntimeError as err:
if attempt == max_attempts:
raise
wait = base_delay * (2 ** (attempt - 1)) + random.uniform(0, 0.15)
print(f"Attempt {attempt} failed ({err}); retrying in {wait:.2f}s...")
time.sleep(wait)If POST /charges times out after reaching Stripe, Stripe may have already charged the card. Always pass an Idempotency-Key header (e.g. a UUID per checkout attempt) before retrying a mutating POST request.
4. Fetching Paginated API Results (Page vs Cursor)
Real APIs never dump 50,000 rows into one JSON response—they paginate using one of two patterns:
- Page / Offset (
?page=2&limit=50): Simple, but if a new item is inserted on page 1 while you fetch page 2, rows shift and you can see duplicates. - Cursor (
?cursor=eyJpZCI6NTB9): Passes an opaque pointer to the last seen record—consistent even on live feeds.
Pairing a yield generator with a pagination loop streams items lazily without loading every page into RAM at once:
def iter_all_pages(fetch_page):
page = 1
while True:
payload = fetch_page(page)
items = payload.get("items", [])
if not items:
break
yield from items
if not payload.get("has_next"):
break
page += 1Try It Yourself in the Playground
Test exponential backoff retries and paginated streaming against a simulated flaky API in the Python sandbox:
Click “Run Code” to execute this snippet right in your browser.
Mini-Challenge: Modify fetch_with_retry so it only retries ConnectionError, and immediately re-raises ValueError (representing a 400 Bad Request client bug) without retrying.
Quick Checkpoints
Why should every httpx or requests call set an explicit timeout=?
Which HTTP error status should you generally NOT retry automatically?