Lesson 40 of 59Libraries every Python developer knows
Calling APIs with requests and httpx
Call other services from Python with requests and httpx, with timeouts, retries, shared clients, auth, error handling and tests.
This unit steps back from FastAPI to the libraries you will meet in almost any Python job, starting with the one every backend needs. Almost every backend calls other backends. You charge a card through Stripe, send an email through a provider, fetch exchange rates, or talk to another team's service. Each of those calls can be slow, can fail, and can return something you did not expect, and your API inherits all of it. This lesson covers the two libraries Python developers reach for, requests and httpx, and the habits that keep an outgoing call from taking your service down with it: timeouts, retries, shared clients and clear error handling.
requests: the classic
requests has been the standard way to make HTTP calls in Python for over a decade. You will find it in scripts, data jobs and most older codebases.
import requests
response = requests.get(
"https://api.example.com/rates",
params={"base": "EUR", "symbols": "USD,GBP"}, # becomes ?base=EUR&symbols=USD%2CGBP
headers={"Accept": "application/json"},
timeout=5,
)
response.raise_for_status() # raise if the status is 4xx or 5xx
data = response.json() # parse the JSON body into dicts and lists
print(data["rates"]["USD"])The pieces you use every day:
params=builds the query string and escapes it for you. Never glue query strings together by hand.json=onrequests.postserialises a dict to JSON and sets theContent-Typeheader.data=sends form fields instead.response.status_code,response.headers,response.textandresponse.json()read the reply.raise_for_status()turns a404or503into an exception. Without it, a failed call returns a response object like any other, and your code happily reads an error page as if it were data.
requests is synchronous only. Inside an async def FastAPI route it blocks the event loop, which the background tasks lesson showed is a serious problem.
httpx: the modern choice
httpx has almost the same API as requests, so moving between them is easy. It adds three things that matter on a backend team:
- Async support through
httpx.AsyncClient, so it fits FastAPI. - A default timeout of five seconds.
requestswaits forever unless you passtimeout=. - Pluggable transports, which make testing without a network clean.
import asyncio
import httpx
# Sync: same shape as requests
response = httpx.get("https://api.example.com/users/1", timeout=5.0)
response.raise_for_status()
print(response.json())
# Async: the same calls, awaited
async def main() -> None:
async with httpx.AsyncClient(timeout=5.0) as client:
users, orders = await asyncio.gather(
client.get("https://api.example.com/users/1"),
client.get("https://api.example.com/orders", params={"user_id": 1}),
)
print(users.json(), orders.json())
asyncio.run(main())One difference catches people: requests follows redirects by default and httpx does not. Pass follow_redirects=True when you want it.
async def FastAPI route calls requests.get(url, timeout=5) and the upstream takes 4 seconds. What happens to other requests on that worker?Timeouts, always
A call with no timeout can hang until the operating system gives up, which can be minutes. While it hangs it holds a worker, a database session, maybe a lock. A slow upstream then turns into a slow you, and enough slow calls pile up into an outage. Every outgoing call needs a timeout, and it should be shorter than the timeout of whoever is calling you.
There are really several timeouts: how long to wait to connect, how long to wait for each chunk of the response to read, and how long to wait to write the request. httpx lets you set them separately:
timeout = httpx.Timeout(10.0, connect=3.0) # 3 s to connect, 10 s for everything else
client = httpx.Client(timeout=timeout)With requests you pass a tuple, timeout=(3, 10), for connect and read. Neither library has a single "the whole call must finish in N seconds" setting by default, so if you need a hard deadline in async code, wrap the call in asyncio.timeout(...).
When a timeout fires you get httpx.TimeoutException (or requests.Timeout). Decide what that means for your user: retry, return cached data, or return a 503 or 504 with a clear message.
Clients, sessions and connection reuse
Every new HTTPS connection costs a DNS lookup, a TCP handshake and a TLS handshake before any data moves. Calling httpx.get(...) or requests.get(...) at the top level opens a fresh connection each time. A client (httpx) or session (requests) keeps a pool of open connections and reuses them, and it is also where you set shared defaults once.
import httpx
github = httpx.Client(
base_url="https://api.github.com",
headers={"Accept": "application/vnd.github+json", "User-Agent": "razorcode-app"},
timeout=httpx.Timeout(10.0, connect=3.0),
)
repo = github.get("/repos/astral-sh/uv") # relative to base_url, reuses the poolIn FastAPI, create one AsyncClient when the app starts and close it on shutdown, using the lifespan handler. Then share it through a dependency.
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from typing import Annotated
import httpx
from fastapi import Depends, FastAPI, Request
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
async with httpx.AsyncClient(base_url="https://api.example.com", timeout=5.0) as client:
app.state.http = client
yield # the app serves requests here
app = FastAPI(lifespan=lifespan)
def get_http(request: Request) -> httpx.AsyncClient:
return request.app.state.http
Http = Annotated[httpx.AsyncClient, Depends(get_http)]
@app.get("/weather/{city}")
async def weather(city: str, http: Http):
response = await http.get("/weather", params={"city": city})
response.raise_for_status()
return response.json()The route asks the shared client. No connection exists yet.
Reading responses carefully
A 200 does not mean the body is what you expect. APIs change, proxies return HTML error pages with a 200, and fields go missing. Treat an upstream response like user input and validate it at the boundary with Pydantic:
from pydantic import BaseModel
class Rates(BaseModel):
base: str
rates: dict[str, float]
def fetch_rates(client: httpx.Client) -> Rates:
response = client.get("/rates", params={"base": "EUR"})
response.raise_for_status()
return Rates.model_validate(response.json())Now the rest of your code works with a typed object, and a surprise in the payload fails right here with a clear ValidationError instead of a KeyError three functions later.
For large downloads, do not load the whole body into memory. Stream it in chunks:
with client.stream("GET", "/exports/orders.csv") as response:
response.raise_for_status()
with open("orders.csv", "wb") as f:
for chunk in response.iter_bytes():
f.write(chunk)Headers and auth
Most APIs want a key or a token. Send it in a header, set once on the client, and load the secret from settings, never from source code.
client = httpx.Client(
base_url="https://api.stripe.com/v1",
headers={"Authorization": f"Bearer {settings.stripe_key}"},
)
# Basic auth (username and password) has a shortcut in both libraries
httpx.get("https://example.com/private", auth=("ada", settings.password))Set a descriptive User-Agent for anything you call often. When something goes wrong, the other side can see who you are and contact you instead of blocking you.
Errors and retries
Calls fail in two different ways, and you handle them differently:
| What went wrong | httpx exception | Retry? |
|---|---|---|
| Could not connect, DNS failed, timed out | httpx.RequestError (and subclasses like httpx.TimeoutException) | Usually yes |
Server answered 429, 502, 503, 504 | httpx.HTTPStatusError from raise_for_status() | Yes, with backoff |
Server answered 400, 401, 404, 422 | httpx.HTTPStatusError | No, the request itself is wrong |
try:
response = await http.post("/charges", json=payload)
response.raise_for_status()
except httpx.HTTPStatusError as exc:
logger.warning("payment API returned %s", exc.response.status_code)
raise PaymentFailed(exc.response.status_code) from exc
except httpx.RequestError as exc:
logger.warning("payment API unreachable: %s", exc)
raise PaymentUnavailable() from excA retry with exponential backoff waits a little, then twice as long, then twice as long again, with some random jitter so a thousand clients do not all retry at the same instant. Here is the whole idea in plain Python:
Press Run (⌘ Enter) to see what happens.In real code you rarely write this loop yourself. Common choices are the tenacity library (a @retry decorator with backoff and stop conditions), httpx.HTTPTransport(retries=3) for connection failures only, or urllib3's Retry mounted on a requests session through an HTTPAdapter.
Only retry what is safe to repeat. A GET is fine. A POST that charges a card is not, unless the API supports an idempotency key: a unique header you send so the server can recognise a repeat and return the first result instead of charging twice.
Match each failure to the sensible response.
With base_delay=0.5 and no jitter, how long does the third wait last (in seconds)?
delay = base_delay * 2 ** (attempt - 1) # waits happen after attempts 1, 2 and 3
Testing code that calls APIs
Tests must not hit real APIs. They would be slow, flaky, and might send real emails. You have three good options:
- A fake transport. httpx accepts
transport=httpx.MockTransport(handler), wherehandleris a function that takes anhttpx.Requestand returns anhttpx.Response. No network is touched, and you can assert on exactly what your code sent. - respx, a library that patches httpx so you declare routes like
respx.get("https://api.example.com/rates").mock(return_value=httpx.Response(200, json={...})). Forrequests, the equivalent is theresponseslibrary. - Inject the client. If your code receives its client through a dependency, a test overrides that dependency with one that uses a mock transport.
import httpx
from app.rates import fetch_usd_rate
def handler(request: httpx.Request) -> httpx.Response:
assert request.url.params["base"] == "EUR"
return httpx.Response(200, json={"rates": {"USD": 1.08}})
def test_fetch_usd_rate():
client = httpx.Client(transport=httpx.MockTransport(handler), base_url="https://api.example.com")
assert fetch_usd_rate(client) == 1.08Test the unhappy paths too: return a 503, raise httpx.ConnectTimeout from the handler, and check that your code retries or fails the way you intended.
AsyncClient in the lifespan handler instead of async with httpx.AsyncClient() inside each route?- timeout
- The longest you wait to connect or read before giving up. Every outgoing call needs one.
- raise_for_status
- A response method that raises an exception if the status code is 4xx or 5xx.
- connection pool
- Open connections kept by a client or session and reused, so calls skip repeated handshakes.
- exponential backoff
- Waiting longer after each failed attempt, usually doubling, before retrying.
- jitter
- Random extra delay added to retries so many clients do not retry at the same moment.
- idempotency key
- A unique value sent with a write so the server can safely ignore a repeated request.
- MockTransport
- An httpx transport that answers requests with a function you write, for tests without a network.