01B.5 HTTP Clients with httpx
Every LLM provider is an HTTP+JSON API, and almost everything else in an AI product talks HTTP too: scraping documentation sites, calling embedding and reranking endpoints, downloading generated images and audio, polling batch jobs, talking to vector databases and MCP servers. This lesson teaches the Python HTTP client you will actually use — httpx — completely: the request/response model, the sync and async clients, connection pooling, timeouts, streaming, Server-Sent Events, uploads and downloads, error handling, testing without a network, and a typed client class you can reuse. Everything is shown on a fake ticket API so no API key and no provider account is needed to learn it.
What you'll learn
- Why a client library beats
urllib, and howhttpx,requests,aiohttpand the SDK-bundled clients compare — including thehttpx2fork the provider SDKs now use - The full request/response surface: parameters, headers,
json=/data=/content=/files=, cookies, redirects, URL building, authentication, content negotiation ClientandAsyncClient: connection pooling, keep-alive, HTTP/2,httpx.Timeout's four phases,httpx.Limits, proxies,trust_envand certificate verification- The complete exception hierarchy: what each error means, which are retryable, and how to log failures without leaking secrets
- Streaming responses:
iter_bytes/iter_text/iter_linesand their async twins, timeouts on streams, cancellation, and Server-Sent Events on the wire (with a small parser you can run) - Uploads and downloads: multipart forms, streaming bodies, progress, and resumable downloads
- Using one shared
AsyncClientunder bounded concurrency (the pattern every later lesson assumes) - Testing HTTP code with
httpx.MockTransport,respx, and a localhttp.serverfake — never the real network aitoolkit/http.py: a typed, configured client with pagination, error mapping and a Pydantic decoding hook
What you don't need
- HTTP itself. Module 00, lesson 6 covers methods, status codes, headers and JSON; this lesson uses that vocabulary without re-teaching it.
async/awaitinternals. 01B.3 owns the event loop; this lesson assumes you can readasync def/awaitand links back when it matters.- Bounded concurrency. 01B.4 owns semaphores and worker pools; here you see only how an HTTP client's pool interacts with them.
- Retries, backoff and
tenacity. 01B.9 owns resilience; this lesson shows where timeouts and transport retries fit, and links forward. - Any API key. Everything runs against a fake local API or mocked transports.
Setup
This lesson continues the aitoolkit project from 01B.1. If you don't have it yet:
uv init aitoolkit --package --python 3.13 && cd aitoolkit
uv add httpx
# or: pip install httpxThe samples were written and checked against httpx 0.28 as of November 2026; if a newer release changes a name or default, check the httpx changelog. The optional extras you'll meet later: uv add "httpx[http2]" installs h2 for HTTP/2, and uv add "httpx[socks]" installs socksio for SOCKS proxies. No .env file is needed — the fake API takes a placeholder token like test-token-123.
What you must be able to do after this lesson#
- Choose between httpx, requests and aiohttp for a given job
- Send requests with parameters, headers and JSON bodies and read the response
- Reuse one Client or AsyncClient with the four timeouts and connection limits set
- Handle httpx exceptions and tell retryable errors from permanent ones
- Stream a response line by line and parse Server-Sent Events
- Test HTTP code with httpx.MockTransport and no real network
Why this matters for an AI engineer#
| You'll hear... | You'll understand it after... |
|---|---|
"The SDK's timeout=60 — what does that actually cover?" |
3.3 httpx.Timeout in depth |
| "Why does everyone say 'create the client once'?" | 3.1 Reuse the client |
| "Our tests are flaky — they hit the real API." | Part 8: Testing HTTP code |
"We got ReadTimeout — is that retryable?" |
the exception tree and 01B.9 |
| "The stream just stops — no error, no end." | 5.2 Timeouts, cancellation and closing streams |
"openai 3.x broke all our httpx mocks." |
1.5 The rest of the field and 03.1 §4.5 |
| "PoolTimeout under load — what gives?" | 7.2 PoolTimeout |
"Why is response.json() exploding on an HTML page?" |
4.3 raise_for_status vs checking status_code |
| "SSE is just text — can I parse it myself?" | 5.3 Server-Sent Events |
Part 1: HTTP in one page, and why you need a client library#
1.1 The 30-second HTTP recap#
An HTTP exchange is a request (method, URL, headers, optional body) answered by a response (status code, headers, body). Module 00 lesson 6 covers the full anatomy — methods, safe/idempotent semantics, status classes, the headers that matter (Content-Type, Authorization, Retry-After, request IDs). This lesson assumes you can read a request and a response; everything below is about making them well from Python.
1.2 urllib: the standard library's answer#
Python ships urllib.request, and it can do real HTTP. Here it is fetching a JSON ticket from a tiny local server — run for real, no third-party packages:
# urllib_demo.py — stdlib only. A local http.server in a thread, fetched with urllib.
import json
import threading
import urllib.error
import urllib.request
from http.server import BaseHTTPRequestHandler, HTTPServer
TICKET = {"id": 42, "subject": "Cannot log in", "status": "open", "priority": "high"}
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/ticket/42":
body = json.dumps(TICKET).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
elif self.path == "/missing":
body = json.dumps({"error": "not_found"}).encode()
self.send_response(404)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
server = HTTPServer(("127.0.0.1", 8931), Handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
with urllib.request.urlopen("http://127.0.0.1:8931/ticket/42") as resp:
print("status:", resp.status)
print("body:", json.loads(resp.read()))
try:
urllib.request.urlopen("http://127.0.0.1:8931/missing")
except urllib.error.HTTPError as e:
print("404 raised:", e.code, e.reason)
server.shutdown()status: 200
body: {'id': 42, 'subject': 'Cannot log in', 'status': 'open', 'priority': 'high'}
404 raised: 404 Not FoundIt works. So why do almost all real codebases use a library? Because urllib makes the easy cases slightly awkward and the hard cases much harder:
- Redirects are invisible.
urlopenfollows 301/302 automatically — you never asked it to, and you can't easily tell it not to. (httpx defaults tofollow_redirects=False— you opt in.) - Errors are exceptions by default. A 404 raises
HTTPErrorbefore you can inspect the body, though the exception object doubles as a response. There's noresponse.status_codeon the happy path — you get a file-like object. - No timeouts by default.
urlopenwithouttimeout=can block forever. (httpx defaults to a strict 5-second timeout on every phase.) - No connection reuse you control. You build an
OpenerDirector/handler chain to get pooling, cookies and auth — essentially assembling the client library yourself. - JSON is
json.loads(resp.read())— fine, but every call site re-implements decoding, error mapping and headers. - Async doesn't exist. No
urllibstory forasyncioat all.
1.3 requests: the incumbent#
For a decade requests was the Python HTTP library — "HTTP for Humans". Its API (requests.get(...), response.json(), session = requests.Session()) is so familiar that httpx deliberately mirrors it.
Two facts you should know as of November 2026:
requestsis synchronous only. There is no asyncrequests. If your code is async — and LLM calls are almost always async — you need a different library regardless.- It is actively maintained again. After years in low-activity limbo it returned to the Python Software Foundation and is shipping regularly: version 2.34.2 was released in May 2026 and the repository sees regular commits. (If you read older posts saying "requests is in maintenance mode", they describe the pre-PSF era.) Sync-only remains its defining limit, not neglect.
requests is still everywhere — plenty of production code uses it, and for purely synchronous scripts it's perfectly good. But it can't do async, its streaming API is clunkier than httpx's, and it has no first-class HTTP/2. For new AI-adjacent code, httpx is the default choice.
1.4 httpx: what it adds#
httpx (currently 0.28.1, BSD-3-Clause) is "the next-generation HTTP client for Python". It keeps requests' familiar surface and adds what modern code needs:
| Capability | What it means for you |
|---|---|
| Sync and async, one API | httpx.Client and httpx.AsyncClient have the same methods; you await the async ones. One mental model covers scripts, workers and web services. |
| HTTP/1.1 and HTTP/2 | http2=True (with the h2 extra) enables multiplexing many requests over one connection — the big win for high-concurrency LLM fan-out. |
| Timeouts everywhere, by default | A strict 5-second timeout on connect/read/write/pool unless you say otherwise. No forgotten-timeout hangs. |
| First-class streaming | client.stream(), iter_bytes/iter_text/iter_lines and async twins — the foundation for SSE and large downloads. |
| Type annotated, testable | Ships types; MockTransport, WSGITransport and ASGITransport make testing without a network a first-class feature. |
| Modern extras | HTTP proxy and SOCKS support, .netrc, brotli/zstd decoding, an optional CLI (httpx[cli]). |
1.5 The rest of the field: aiohttp, SDK clients and httpx2#
aiohttp (3.14.x) is the other serious async HTTP library — and also a server framework. It's mature and fast under very high concurrency, but its API is async-only and less requests-familiar. You'll meet it as an optional backend for the provider SDKs in 03.9; for your own HTTP code, httpx is the simpler default.
SDK-bundled clients. The provider SDKs don't use httpx directly any more. openai 3.x and anthropic 2.x depend on httpx2, Pydantic's maintained fork of httpx (see 03.1 §4.5); google-genai 2.34.0 (the version the Module 03 samples were checked against) defaults to httpx but can switch; its 3.x line, released in November 2026 and the release an unpinned install now gives you, flips that default to httpx2 and makes httpx an extra, so check which one your installed version declares. That matters for two reasons you'll see in Part 8: respx patches httpx only, and httpx2's classes are different types even though the API is nearly identical. When you write HTTP code yourself — a crawler, an internal API client, a webhook receiver's test — the question is which library to import:
| Situation | Use |
|---|---|
| Your own new code, no SDK constraints | httpx — biggest ecosystem, respx works, most tutorials target it |
Your project already pulls in openai/anthropic 3.x/2.x and you want one HTTP stack |
httpx2 — same API shape, maintained by Pydantic, OS trust store for certificates |
google-genai is your only SDK |
Either works; httpx is the default in 2.34.0, httpx2 in 3.x |
| You need a server too | aiohttp, fastapi+httpx for the client side (01B.7) |
| Purely synchronous one-off script | requests is fine; httpx sync client is equally fine |
1.6 Decision table: which to import#
Writing HTTP client code yourself?
├── Need async? ──────────────── no ──> requests (fine) or httpx sync (better)
│ yes ──> httpx.AsyncClient (default)
│ └── project already on openai/anthropic SDKs? → httpx2
├── Need a server as well? ────── yes ──> aiohttp, or FastAPI (01B.7) + httpx client
├── Testing SDK calls? ────────── yes ──> MockTransport of the SAME library the SDK uses
│ (httpx2.MockTransport for openai/anthropic — 03.10 §7.4)
└── Just poking an API once? ──── yes ──> httpx CLI (`uvx --from 'httpx[cli]' httpx get ...`) or curlPart 2: Requests and responses#
2.1 Top-level functions vs a Client#
The simplest way to send a request is a top-level function:
import httpx
r = httpx.get("https://api.example.com/tickets", params={"status": "open"})
print(r.status_code) # 200
print(r.json()) # parsed JSON body (dict/list)Under the hood, each top-level call builds a fresh Client, makes the request and closes it — convenient, but it means a brand-new TCP+TLS connection per call and no shared state (cookies, headers). The docs are blunt about it: if you do anything more than a one-off script, use a Client.
with httpx.Client(base_url="https://api.example.com", headers={"X-App": "aitoolkit"}) as client:
r = client.get("/tickets", params={"status": "open"})
r.raise_for_status()
tickets = r.json()["items"]A Client is the requests.Session() equivalent: it owns a connection pool (reused keep-alive connections to each host), default headers/params/cookies/auth, and proxy/TLS/timeout configuration applied to every request. Use async with httpx.AsyncClient(...) for the async version — same arguments, awaited methods.
2.2 The Response object#
Every call returns a Response. The attributes you'll use constantly:
| Attribute / method | What it gives you |
|---|---|
r.status_code |
The integer status (200, 404, 429...). Compare with httpx.codes.OK etc. |
r.is_success / r.is_error / r.is_redirect |
True for 2xx / 4xx-5xx / 3xx — cheap checks before parsing |
r.headers |
A case-insensitive dict-like Headers object (r.headers["content-type"] works either case). Multi-value headers arrive comma-joined per RFC 9110. |
r.text |
The body decoded to str. Encoding comes from the Content-Type charset, else UTF-8 by default (3.6 covers overrides). |
r.content |
The raw body as bytes — for binary downloads and hashing. |
r.json() |
json.loads(r.content) essentially — raises json.JSONDecodeError (a plain ValueError subclass), not an httpx error, on non-JSON bodies. |
r.url |
The final httpx.URL actually requested, including merged params. |
r.request |
The Request that produced it — method, headers, content. Invaluable in logs and error messages. |
r.elapsed |
timedelta of the exchange (once the response is read). |
r.http_version |
"HTTP/1.1", "HTTP/2" etc. — tells you whether HTTP/2 actually negotiated. |
r.cookies |
Cookies set by this response; the client's jar persists them across requests. |
r.links |
Parsed Link: headers (RFC 8288) — pagination APIs love this. |
r.next_request |
On a redirect response, the Request it points to. |
r.history |
On the final response after redirects, the chain of earlier responses. |
r.iter_bytes() / iter_text() / iter_lines() / iter_raw() |
Streaming readers (Part 5). iter_raw skips content decoding (still de-chunked). |
r.read() / r.aread() |
Force-load a streamed body into memory. |
r.raise_for_status() |
Raises HTTPStatusError on any non-2xx status (1xx/3xx included), returns self on 2xx — chainable. |
A few traps worth memorising now:
r.json()on an HTML error page raisesJSONDecodeError— that's how "the API returned a Cloudflare block page" shows up in your logs. Checkr.status_code/raise_for_status()before.json(). (4.3 is entirely about this.)r.textis a guess when no charset is declared. httpx defaults to UTF-8; if the server lies, you get mojibake. Setclient = httpx.Client(default_encoding="shift-jis")or achardet/charset-normalizercallable for auto-detection.r.contenton a streamed response raisesResponseNotReaduntil you callr.read()— Part 5 covers the rules.
2.3 Sending data: params, headers, json=, data=, content=, files=#
client.post(
"/tickets",
params={"dry_run": "true"}, # -> ?dry_run=true in the URL
headers={"Idempotency-Key": "req-1042"}, # per-request headers
json={"subject": "Cannot log in", "priority": "high"}, # JSON body + Content-Type: application/json
)| Parameter | Sends | Content-Type it sets |
|---|---|---|
params= |
Query string (dict, list of pairs, or string; values may be lists → repeated keys) | — |
headers= |
Extra headers (merged with client defaults, case-insensitively) | — |
json= |
Body as JSON via json.dumps |
application/json |
data= |
Form-encoded body (dict; values may be lists → repeated fields) | application/x-www-form-urlencoded |
files= |
Multipart body — see below | multipart/form-data; boundary=... |
content= |
Raw body: bytes, str, or an iterator of bytes chunks |
whatever you set (or none) |
data= + files= together produces multipart with regular fields alongside files. To control a file's filename and MIME type, pass a tuple: files={"upload": ("report.pdf", fileobj, "application/pdf")}. For binary bodies without multipart, content=b"..." or a generator of bytes — which is also how you get upload progress and streaming uploads (Part 6).
2.4 Cookies, redirects and URL building#
- Cookies:
client.cookiesis aCookiesjar persisted across requests on that client. Per-requestcookies={...}merges in.response.cookiesshows what one response set. The jar handles domain/path/expiry rules for you — don't hand-rollCookieheaders. - Redirects:
follow_redirects=True(on the client or per request) makes httpx follow 301/302/303/307/308, rebuilding the method and body per the rules (303 always becomes GET; 307/308 preserve method and body). The default isFalse— unlikerequests, which follows by default.response.historyholds the chain;response.next_requestthe immediate hop. More than ~20 hops raisesTooManyRedirects. - URLs: pass strings or
httpx.URL.params=handles encoding; pass a list of tuples for repeated keys.base_urlon the client prepends to relative paths —client.get("/tickets")withbase_url="https://api.example.com/v1"hitshttps://api.example.com/v1/tickets. httpx's joining rule is simpler than RFC 3986 resolution (and different fromurllib.parse.urljoin): it always appends the request path to the base — the client forces a trailing/ontobase_urland strips leading/from the request path — soget("/tickets")andget("tickets")produce the identical URLhttps://api.example.com/v1/tickets. The only way to leave the base path entirely is to pass an absolute URL. Internationalised domain names are encoded via IDNA automatically.
2.5 Authentication#
# HTTP Basic via a (username, password) tuple — httpx encodes the header for you
client = httpx.Client(auth=("alice", "s3cret"))
# Bearer tokens are just a header — the common case for APIs
client = httpx.Client(headers={"Authorization": "Bearer sk-..."})
# Digest auth and netrc also exist; custom flows via an Auth class
class TokenAuth(httpx.Auth):
def __init__(self, token: str) -> None:
self.token = token
def auth_flow(self, request):
request.headers["Authorization"] = f"Bearer {self.token}"
yield request # a generator: may yield the request, then a refreshed one on 401Keep credentials out of URLs (https://user:pass@host leaks into logs and r.url) — use auth= or headers, and remember .netrc files are honoured when trust_env=True (the default).
2.6 Status codes and raise_for_status()#
raise_for_status() raises httpx.HTTPStatusError for any non-2xx status — 1xx, 3xx, 4xx and 5xx all raise; only a 2xx returns self. (The exception's own docstring still says "4xx or 5xx", but the code checks is_success — 200–299 — and raises for everything else; httpx's test suite asserts that even 101 and 303 raise.) The exception carries .response and .request, and its message is genuinely useful — for a 404 it reads Client error '404 Not Found' for url 'https://...' followed by a For more information check: https://developer.mozilla.org/... line pointing at the status-code docs.
Because it returns self on success, the idiomatic chain is:
r = client.get("/tickets/42").raise_for_status()
ticket = Ticket.model_validate(r.json()) # Pydantic arrives in 01B.6Whether you should raise depends on the caller: library code often returns the response and lets the application decide (a 404 might be a legitimate "not found" result), while scripts and internal tools benefit from failing fast. Pick one convention per codebase and document it — mixing "sometimes raises, sometimes returns" is how bugs hide.
2.7 Content negotiation: Accept and Accept-Encoding#
Two headers run the negotiation between what you can handle and what the server can send — one for media type, one for compression.
Accept says which media types the client can parse. httpx sends Accept: */* by default ("anything"); set it explicitly when the endpoint can return several representations — Accept: application/json on JSON APIs, Accept: text/event-stream on SSE endpoints (the httpx-sse helper sets it for you, 5.4; provider APIs have their own conventions, 03.1/03.3). Entries can carry quality values — Accept: text/csv;q=1.0, application/json;q=0.5 — which most APIs ignore but caches and CDNs honour. Remember the asymmetry: Accept is what you request; the response's Content-Type is what the body actually is — check it (or the status) before .json() (4.3).
Accept-Encoding advertises which compressed forms you'll accept, and httpx handles it for you: every client sends Accept-Encoding: gzip, deflate automatically — adding br (brotli) and zstd when you install the [brotli]/[zstd] extras — and transparently decodes whatever Content-Encoding the response carries (6.2). You rarely set it yourself; if you do, it replaces the default for that request, so only advertise encodings whose decoder is installed — a Content-Encoding httpx has no decoder for is silently passed through as still-compressed bytes.
The response side of the negotiation is Vary: a header telling caches which request headers the response depends on. Vary: Accept-Encoding means "this body was chosen based on your Accept-Encoding — don't serve the gzip variant to a client that didn't ask for it". CDNs, corporate proxies and browser caches all honour it; when you build your own compressing endpoints later (01B.7), the framework sets it for you — but when you debug "why did the CDN serve me compressed garbage", Vary is the first header to check.
GET /exports/tickets.csv HTTP/1.1
Host: api.example.com
Accept: text/csv
Accept-Encoding: gzip, deflate <- added automatically by httpx
HTTP/1.1 200 OK
Content-Type: text/csv
Content-Encoding: gzip <- httpx decodes this for you
Vary: Accept-Encoding <- caches key their stored copy on it# Narrow Accept when the endpoint serves several media types.
# Leave Accept-Encoding alone unless you have a reason — and if you do
# set it, only list encodings you can decode (gzip/deflate always;
# br needs `uv add "httpx[brotli]"`, zstd needs `uv add "httpx[zstd]"`).
client = httpx.Client(headers={"Accept": "application/json"})Part 3: The Client: pooling, timeouts and limits#
3.1 Reuse the client: connection pooling and keep-alive#
flowchart LR
subgraph app ["Your code"]
T1["task 1"]
T2["task 2"]
T3["task N"]
end
C["httpx.AsyncClient<br/>(one per process)"]
P["connection pool<br/>keep-alive TCP/TLS conns"]
H["api.example.com:443"]
T1 & T2 & T3 --> C
C --> P
P -- "reused connections" --> HEvery request through a Client/AsyncClient goes through its connection pool: open TCP (and TLS) connections to each host are kept alive and reused. The handshake — DNS, TCP, TLS negotiation — costs tens to hundreds of milliseconds; reusing a connection costs nothing. Under an LLM workload (hundreds of calls to one host per minute) pooling is the difference between "fast" and "saturated".
The rules, which 03.9 §2.3 enforces for provider SDKs too:
- Create the client once, share it. Never
httpx.Client()inside a loop or per request — that defeats pooling entirely. - Close it:
with/async withblocks, or.close()/await .aclose()infinally. Unclosed clients leak sockets and file descriptors, and httpx does not reliably warn you (theUnclosed client sessionmessage people remember comes fromaiohttp), so the leak stays silent until the process runs out of connections. - One event loop per async client. An
AsyncClient's pool belongs to the loop it first ran on — don't share it across twoasyncio.run()calls. - Sync client in async code blocks the loop.
client.get()insideasync defstalls every other task — useAsyncClient(orasyncio.to_threadfor genuinely blocking libraries; 01B.3 covers the mechanics).
3.2 Context managers and per-client defaults#
Everything you can pass per request, you can pass once to the constructor: base_url, headers, params, cookies, auth, timeout, limits, proxy/mounts, verify, trust_env, follow_redirects, http2, event_hooks, transport.
When both levels set the same thing, httpx merges predictably:
- headers, params, cookies merge — client values plus request values (headers case-insensitively; a request header overrides the client's for the same name).
- the request wins for the settings that can be overridden per call —
timeout,authandfollow_redirects.verify,proxy/mounts,limits,http2,trust_envandtransportare client-only: they are fixed when the client is built, so a different value means a different client.
So the pattern is: put shared config on the client (base URL, auth header, default timeout, UA string) and only per-call variation on the request.
3.3 httpx.Timeout in depth#
The single most important knob in this lesson. httpx has four timeout phases, each guarding a different wait:
| Phase | Guards the wait for... | Typical value |
|---|---|---|
connect |
TCP+TLS handshake to the host | 2–5 s — if you can't connect in 5 s, the network is broken |
read |
The next chunk of response data — not the total response time | Long enough for the slowest silence you tolerate |
write |
Sending the request body | Rarely matters except large uploads |
pool |
A free connection from the pool | Matters under concurrency; too small → PoolTimeout |
# All four set explicitly
timeout = httpx.Timeout(30.0, connect=5.0) # 30 s read/write/pool, 5 s connect
client = httpx.Client(timeout=timeout)
# Or per request
client.get("/tickets", timeout=10.0)
client.get("/reports", timeout=None) # disable — almost never right3.4 httpx.Limits: sizing the pool#
limits = httpx.Limits(
max_connections=100, # hard cap on open connections per host (default 100)
max_keepalive_connections=20, # how many stay open for reuse (default 20)
keepalive_expiry=5.0, # seconds an idle conn stays pooled (default 5)
)
client = httpx.AsyncClient(limits=limits)Defaults are sane for scripts; under high async concurrency raise max_connections/max_keepalive_connections to match your semaphore (01B.4) — but remember the pool timeout: when all connections are busy, the next request waits up to pool seconds for one, then raises PoolTimeout. A PoolTimeout storm is your semaphore and pool disagreeing, not the network failing (7.2).
3.5 HTTP/2#
uv add "httpx[http2]" # installs h2client = httpx.AsyncClient(http2=True)
r = await client.get("https://example.com")
print(r.http_version) # "HTTP/2" if the server supports it, else "HTTP/1.1"HTTP/2 multiplexes many requests over one TCP connection and compresses headers — valuable when you're firing hundreds of concurrent calls at one host (LLM APIs included). It's opt-in because HTTP/1.1 is the mature path; enable it for high-concurrency clients, then check r.http_version to confirm it actually negotiated (the server must support it too). Note the pool accounting changes subtly: one connection carries many streams, so max_connections means something different — don't tune blindly.
3.6 Proxies, trust_env and certificates#
- Proxies:
httpx.Client(proxy="http://proxy.corp:8080")routes all traffic;mounts={"https://": httpx.HTTPTransport(proxy=...), "http://": ...}routes per scheme; credentials go in the URL userinfo (http://user:pass@proxy:8080). SOCKS needshttpx[socks]. Thehttps://mount typically still uses anhttp://proxy URL — the proxy connection itself is plain HTTP, then tunnels TLS (HTTPCONNECT). trust_env=True(default) makes httpx honourHTTP_PROXY,HTTPS_PROXY,ALL_PROXY,NO_PROXY,SSL_CERT_FILE,SSL_CERT_DIRand.netrc. That's what you want on a laptop behind a corporate proxy — and the reasontrust_env=Falseexists for tests and reproducible CI.verify=:True(default) verifies against thecertifibundle;Falsedisables verification — a debugging escape hatch that must never ship; or anssl.SSLContext/CA-bundle path for corporate MITM proxies. (httpx2instead uses the OS trust store viatruststore— relevant when a slim container lacks CA certs; 03.1 §4.5 covers the failure mode.)
3.7 Event hooks and custom transports#
Event hooks are callables fired on every request/response — the clean way to add logging, tracing or metrics without wrapping every call:
async def log_response(response: httpx.Response) -> None:
print(f"{response.request.method} {response.request.url} -> {response.status_code}")
client = httpx.AsyncClient(event_hooks={"response": [log_response]})Two rules: hooks are lists (register several), and on AsyncClient they must be async def — a plain function fails at the first request. Response hooks run before the body is read; call await response.aread() inside the hook if you need response.text/.json() there. (03.10 §2.3 builds a redacting wire logger on exactly this.)
Custom transports are the escape hatch under everything: httpx.HTTPTransport/AsyncHTTPTransport configure the real network layer (retries=, local_address, uds for Unix sockets); WSGITransport/ASGITransport route requests into a Python web app in-process — the backbone of FastAPI/Flask testing (01B.7, 03.10); MockTransport answers with your own handler (Part 8); the mounts= argument routes different URL patterns to different transports (per-host proxies, per-service mocks). Subclass httpx.BaseTransport/AsyncBaseTransport for anything exotic.
Part 4: Errors — the exception hierarchy#
4.1 The tree#
httpx's exceptions (verified against the 0.28.1 source) form a clean tree. Knowing which branch an error lives on tells you what to do about it:
HTTPError <- catch-all for request() + raise_for_status()
├── RequestError <- the request never got a usable response
│ ├── TransportError <- failed below HTTP (network/timeout/protocol)
│ │ ├── TimeoutException
│ │ │ ├── ConnectTimeout <- TCP/TLS handshake too slow
│ │ │ ├── ReadTimeout <- gap between received chunks too long
│ │ │ ├── WriteTimeout <- sending the body too slow
│ │ │ └── PoolTimeout <- waited too long for a pooled connection
│ │ ├── NetworkError
│ │ │ ├── ConnectError <- DNS, refused, TLS verify failed, reset
│ │ │ ├── ReadError / WriteError / CloseError
│ │ ├── ProtocolError
│ │ │ ├── LocalProtocolError <- YOUR bug (bad request you built)
│ │ │ └── RemoteProtocolError<- server sent malformed HTTP
│ │ ├── ProxyError <- proxy CONNECT failed
│ │ └── UnsupportedProtocol <- e.g. ftp:// URL
│ ├── DecodingError <- response body wouldn't decode
│ └── TooManyRedirects <- redirect loop / > ~20 hops
└── HTTPStatusError <- raise_for_status() on any non-2xx (has .response)
Outside HTTPError entirely:
InvalidURL, CookieConflict <- your bug, not the network's
StreamError (RuntimeError) <- stream API misuse
├── StreamConsumed / StreamClosed / ResponseNotRead / RequestNotRead4.2 What each means — and is it retryable?#
| Exception | What happened | Retry? |
|---|---|---|
ConnectTimeout, ConnectError |
Couldn't reach the host (DNS, refused, TLS, reset before response) | Usually yes — the request never arrived |
ReadTimeout, ReadError |
Connection opened, then stalled/dropped mid-response | Maybe — for GETs yes; for POSTs the server may have processed it (01B.9 owns idempotency) |
WriteTimeout, WriteError |
Couldn't send the request | Usually yes |
PoolTimeout |
Pool exhausted — your concurrency problem, not the network's | Fix limits/semaphore first; retrying just queues again |
RemoteProtocolError |
Server sent garbage / dropped mid-chunked-body | Sometimes — transient LB behaviour happens |
LocalProtocolError, InvalidURL, UnsupportedProtocol |
Bug in your code | Never — fix the code |
DecodingError |
Malformed charset/content-encoding | Check the endpoint; rarely transient |
TooManyRedirects |
Redirect loop | Never — fix the URL/config |
HTTPStatusError |
Got a response, status was non-2xx (raise_for_status raises on 1xx/3xx too) |
Depends on the status — 01B.9 owns the retry table; 429/5xx yes, 400/401/404 no |
StreamError family |
Read a stream wrong (consumed twice, before read(), after close) |
Never — programming error |
Every RequestError carries .request (and HTTPStatusError also .response), so exc.request.url is safe to log — but remember the URL can contain secrets in query strings (?key=..., signed URLs). 03.8 §2.2 shows what SDK exceptions add on top.
4.3 raise_for_status() vs checking status_code#
The two idioms:
# A) raise — good for scripts, workers, "the API must work" paths
r = client.get("/tickets/42").raise_for_status()
# B) check — good when non-2xx is a legitimate outcome
r = client.get("/tickets/42")
if r.status_code == 404:
return None # "not found" is data, not failure
r.raise_for_status()The trap that produces the most production bugs: r.json() on an error page. A WAF, proxy or framework error often returns 200-looking HTML or a JSON error body with a 4xx/5xx status. Parsing without checking gives you JSONDecodeError (or worse, a valid JSON error object that looks like data). Rule: status check first, parse second — raise_for_status() or an explicit is_success/status_code branch.
4.4 Logging failures without leaking secrets#
def safe_url(url: httpx.URL) -> str:
"""Log the URL without query secrets."""
return str(url.copy_with(query=None))
try:
r = client.get("/tickets", params={"api_key": settings.api_key})
r.raise_for_status()
except httpx.HTTPStatusError as e:
log.warning("ticket API %s -> %s", safe_url(e.request.url), e.response.status_code)
except httpx.RequestError as e:
# .request is attached to every error raised through client.* — httpx
# sets it via request_context. Don't write `if e.request`: the property
# raises RuntimeError (it never returns None) when unset.
log.warning("ticket API unreachable: %s %s", type(e).__name__,
safe_url(e.request.url))Two habits: log the exception type + status + sanitised URL, never str(e) blindly (messages can embed URLs with keys), and remember Authorization headers live on e.request.headers — don't dump whole request objects into logs. 12.7, Part 3 owns secret-handling policy; 01B.2 owns where keys live.
Part 5: Streaming#
5.1 client.stream() and the iter_* family#
For large bodies — downloads, SSE token streams, anything you don't want fully in memory — don't call client.get() (which reads the whole body). Stream it:
with httpx.Client(timeout=httpx.Timeout(30.0, connect=5.0)) as client:
with client.stream("GET", "/reports/quarterly.csv") as r:
r.raise_for_status()
for chunk in r.iter_bytes(): # raw bytes as they arrive
sink.write(chunk)| Method | Yields | Use for |
|---|---|---|
iter_bytes(chunk_size=None) |
bytes chunks |
binary downloads, hashing |
iter_text() |
decoded str chunks |
text processing |
iter_lines() |
lines without endings | line-oriented protocols (NDJSON, logs) |
iter_raw() |
bytes before content decoding (still de-chunked) | when you handle gzip yourself |
aiter_bytes/aiter_text/aiter_lines/aiter_raw |
async twins | AsyncClient — async for chunk in r.aiter_bytes() |
r.read() / await r.aread() |
— | buffer the rest into memory inside the stream |
The with client.stream(...) block must stay open while you iterate — exiting closes the response and releases the connection. Inside it, r.text/r.content/r.json() raise ResponseNotRead until you call r.read() (or await r.aread()), so buffer the body inside the block if you need it whole. Async "manual mode" (client.send(req, stream=True)) is the same shape but you must await r.aclose() yourself — forgetting it leaks pool connections.
5.2 Timeouts, cancellation and closing#
- Read timeout on a stream = longest allowed silence between chunks, not total duration. A slow-but-alive SSE stream won't time out; a stalled one will — which is exactly what you want (03.3 §8.1 works the LLM cases).
- Cancellation: breaking out of
async fordoesn't automatically close — wrap inasync with client.stream(...)ortry/finally: await r.aclose(). Leaked streams hold pool connections until GC. StreamConsumed/StreamClosedmean you iterated twice or after close — read once, or buffer withr.read().
5.3 Server-Sent Events: the wire format#
SSE is how LLM APIs stream (text/event-stream): plain UTF-8 text, field: value lines, a blank line dispatches an event, data: lines join with \n, lines starting : are comments/keep-alives, and [DONE] (or the provider's equivalent) is just a data: payload signalling the end. 00.6 introduces the format; 03.3 §2.1 has the complete spec table (event:, id:, retry: semantics); 03.3 §2.5 has the production-grade incremental parser.
Here is the small version — enough for LLM token streams, run for real (stdlib only, any chunking):
# sse_parse.py — minimal SSE parser over byte chunks. Run: python3 sse_parse.py
import codecs
SSE_FIXTURE = b"""\
: keep-alive
event: ticket
data: {"id": 42}
id: 7
data: {"part": "one"
data: , "part": "two"}
event: done
data: [DONE]
"""
def iter_sse_lines(chunks):
"""Yield text lines from raw byte chunks of any size."""
decoder = codecs.getincrementaldecoder("utf-8")()
buffer = ""
for chunk in chunks:
buffer += decoder.decode(chunk)
*lines, buffer = buffer.split("\n")
for line in lines:
yield line
if buffer:
yield buffer
def sse_events(chunks):
"""Parse an SSE byte stream into (event_type, data) pairs.
Keeps what LLM streams use: 'data:' lines accumulated until a blank
line dispatches the event, ':' comments ignored, 'message' default
event type. 'id:'/'retry:' skipped — 03.3 has the full parser.
"""
event_type = "message"
data_lines = []
for raw in iter_sse_lines(chunks):
line = raw.rstrip("\r")
if line == "":
if data_lines:
yield event_type, "\n".join(data_lines)
event_type, data_lines = "message", []
elif line.startswith(":"):
continue
elif line.startswith("data:"):
value = line[5:]
if value.startswith(" "):
value = value[1:]
data_lines.append(value)
elif line.startswith("event:"):
value = line[6:]
event_type = value[1:] if value.startswith(" ") else value
print("=== whole-buffer parse ===")
for event, data in sse_events([SSE_FIXTURE]):
print(f"event={event!r} data={data!r}")
print("\n=== byte-at-a-time chunking ===")
chunks = [SSE_FIXTURE[i:i + 1] for i in range(len(SSE_FIXTURE))]
for event, data in sse_events(chunks):
print(f"event={event!r} data={data!r}")=== whole-buffer parse ===
event='ticket' data='{"id": 42}'
event='message' data='{"part": "one"\n, "part": "two"}'
event='done' data='[DONE]'
=== byte-at-a-time chunking ===
event='ticket' data='{"id": 42}'
event='message' data='{"part": "one"\n, "part": "two"}'
event='done' data='[DONE]'The byte-at-a-time run proves the incremental decoder + line buffer cope with any network chunk boundary — a multi-byte UTF-8 char or a line split across packets is handled. With httpx you'd feed it response.iter_bytes() (or aiter_bytes()); the parser doesn't care about chunk sizes. Caveats this small version skips (all covered by 03.3's parser): lone-CR line endings, the BOM, id:/retry: fields, and a final event missing its trailing blank line.
5.4 httpx-sse#
httpx-sse (0.4.3, MIT — pinned, it's beta) wraps this: connect_sse(client, "GET", url) / aconnect_sse(...) give an EventSource with .iter_sse()/.aiter_sse() yielding ServerSentEvent objects (.event, .data, .id, .retry, .json()). It sets the right Accept/Cache-Control headers and checks Content-Type: text/event-stream. No built-in reconnection — httpx.ReadError propagates and you retry with Last-Event-ID yourself. For provider streams, the SDKs already parse SSE for you — you only need this layer for your own SSE endpoints or unusual providers (01B.7 serves them; 03.3 consumes the providers').
Part 6: Uploads and downloads#
Deep-dive
6.1 Uploads: multipart, streaming bodies and progress#
Small files go through files=:
with open("invoice.pdf", "rb") as f:
r = client.post("/tickets/42/attachments",
files={"file": ("invoice.pdf", f, "application/pdf")},
data={"caption": "scan from post"}) # extra form fields alongsideFor large uploads you don't want the whole file in memory — pass a generator of bytes as content= (sync) or an async generator (async client), and the body streams chunked:
def file_chunks(path: str, size: int = 1024 * 1024):
with open(path, "rb") as f:
while chunk := f.read(size):
yield chunk
# report progress here: bytes_sent += len(chunk)
client.post("/uploads", content=file_chunks("big.zip"),
headers={"Content-Type": "application/zip"})httpx sends it with Transfer-Encoding: chunked (no Content-Length needed) and you can report progress from inside the generator — that's the only hook you get, since the request body is produced lazily. write timeout still applies per chunk.
6.2 Downloads: to disk, progress, and resume#
with client.stream("GET", "/exports/tickets.jsonl") as r:
r.raise_for_status()
total = int(r.headers.get("Content-Length", 0)) # may be absent (chunked)
done = 0
with open("tickets.jsonl", "wb") as f:
for chunk in r.iter_bytes():
f.write(chunk)
done += len(chunk)
# progress: done/total if total else done bytes so farContent-Lengthmay be missing on chunked or otherwise streamed responses — a gzipped body normally still carries one, measuring the compressed bytes. Show bytes-sent instead of a percentage, or user.num_bytes_downloaded, which counts bytes as received on the wire and so is still content-encoded: for a gzipped download it tracks the compressed size — exactly whatContent-Lengthmeasures, so the pair works correctly for progress reporting.- Compression is transparent:
Content-Encoding: gzip/br/zstdbodies are decoded for you (iter_rawskips that if you need the wire bytes). - Resumable downloads are a server feature:
Range: bytes=N-→206 Partial Content. httpx sends whatever headers you give it; whether the API honours ranges is the API's business. For flaky connections to big files (model weights, datasets — Module 09 downloads generated media the same way), implement retry-with-Rangeyourself — 01B.9 for the retry machinery.
Part 7: AsyncClient in practice#
7.1 One shared client under bounded concurrency#
The pattern every later lesson assumes (01B.3 owns async, 01B.4 owns the semaphore):
import asyncio
import httpx
LIMIT = 20 # in-flight requests — tune to the API's rate limit
async def fetch_ticket(client: httpx.AsyncClient, ticket_id: int) -> dict:
r = await client.get(f"/tickets/{ticket_id}")
r.raise_for_status()
return r.json()
async def main() -> None:
sem = asyncio.Semaphore(LIMIT)
async with httpx.AsyncClient(base_url="https://api.example.com/v1",
timeout=httpx.Timeout(30.0, connect=5.0),
limits=httpx.Limits(max_connections=LIMIT * 2)) as client:
async def bounded(tid: int) -> dict:
async with sem:
return await fetch_ticket(client, tid)
results = await asyncio.gather(*(bounded(i) for i in range(1, 101)))
print(len(results), "tickets fetched")
asyncio.run(main())One AsyncClient is safe to share across tasks in the same event loop — that's the whole point of the pool. Size limits.max_connections to roughly your concurrency (a bit above the semaphore so keep-alive conns are available), and let the semaphore — not the pool — be your rate limiter.
7.2 PoolTimeout: the symptom of too much concurrency#
When more requests are in flight than max_connections, the extras wait for a pooled connection up to the pool timeout (default 5 s — easily hit under fan-out). Symptom: bursts of httpx.PoolTimeout while the network is fine. It's a client-side queue overflow, not a server problem: lower your semaphore, raise max_connections, or both. 03.9 §4.6 measures exactly this against provider clients.
7.3 Async streaming and async uploads#
async with client.stream("GET", "/stream/tickets") as r:
async for line in r.aiter_lines():
...
async def aiter_file(path: str):
with open(path, "rb") as f:
while chunk := f.read(1024 * 1024):
yield chunk
await client.post("/uploads", content=aiter_file("big.zip"))Event hooks on AsyncClient must be async def (§3.7); response hooks that read the body need await response.aread().
Part 8: Testing HTTP code#
8.1 httpx.MockTransport: the cleanest fake#
MockTransport takes a handler function that sees each Request and returns a Response — no network, no sockets, works for both sync and async clients:
import httpx
def handler(request: httpx.Request) -> httpx.Response:
if request.url.path == "/tickets/42":
return httpx.Response(200, json={"id": 42, "status": "open"})
return httpx.Response(404, json={"error": "not_found"})
def make_client() -> httpx.Client:
return httpx.Client(transport=httpx.MockTransport(handler),
base_url="https://api.example.com")
with make_client() as client:
assert client.get("/tickets/42").json()["id"] == 42
assert client.get("/nope").status_code == 404Because the handler gets the real Request object, you can assert on method, URL, headers and body — and return sequences of responses to test retries and error paths (a 429 then a 200). For async, the handler is async def returning httpx.Response, used with httpx.AsyncClient(transport=httpx.MockTransport(handler)). This is the same mechanism the SDKs use when you pass http_client= — 03.10 builds a whole testing strategy on it.
8.2 respx — and its limits#
respx (0.23.1) patches httpx's transport so route patterns (respx.get("https://api.example.com/tickets")) answer with canned responses, with a pytest fixture. Elegant for tests — but it patches httpx only. Since openai 3.x/anthropic 2.x moved to httpx2, a "mocked" SDK call can silently hit the real network. 03.10 §7.4 documents the trap and the guard; for your own httpx code respx is fine (uv add --dev respx).
8.3 A local fake server with http.server#
When you want real HTTP semantics — redirects, chunked encoding, actual sockets — stdlib http.server in a thread is the honest fake (this is what the urllib_demo.py in 1.2 does). Pattern: bind 127.0.0.1, serve_forever in a daemon thread, shutdown() in teardown. Use it to test your client's redirect following, timeout behaviour and streaming — deterministically, offline. 01B.8 wraps this in fixtures.
8.4 Never hit real APIs in tests#
The rule that keeps CI fast, free and deterministic: tests use MockTransport, respx, ASGITransport/WSGITransport, or a local fake server — never the real network. Live smoke tests are a separate, opt-in suite with a spending cap (03.10 owns that whole subject; the verify-before-you-trust habits of 00.8 — Reading API Documentation apply). A pytest-socket-style guard that fails any real connection attempt is cheap insurance.
Part 9: A typed client — aitoolkit/http.py#
Putting it together: a reusable client for the lesson's fake ticket API. The API (fictional, documented here so the code makes sense):
GET /v1/tickets?status=&cursor=→{"items": [...], "next_cursor": "..."|null}GET /v1/tickets/{id}→ a ticket object, or404POST /v1/tickets(JSON body) →201+ the created ticket- Bearer auth via
Authorization: Bearer <token>; errors as{"error": {"code", "message"}}
# src/aitoolkit/http.py — configured sync + async clients for the ticket API.
# Pydantic models (Ticket, TicketIn) arrive in 01B.6; retries in 01B.9.
from __future__ import annotations
import httpx
BASE_URL = "https://tickets.example.com/v1"
TIMEOUT = httpx.Timeout(30.0, connect=5.0, pool=10.0)
class TicketAPIError(Exception):
"""Domain error: carries the HTTP status and the API's error code."""
def __init__(self, status: int, code: str, message: str) -> None:
super().__init__(f"{status} {code}: {message}")
self.status = status
self.code = code
def _raise_for_api(r: httpx.Response) -> None:
"""Map httpx outcomes onto TicketAPIError; 404 stays an exception the
caller can catch, transport errors propagate as httpx.RequestError."""
if r.is_success:
return
try:
err = r.json().get("error", {})
code, message = err.get("code", "http_error"), err.get("message", r.reason_phrase)
except (ValueError, AttributeError): # non-JSON body (WAF page) or JSON that isn't an object
code, message = f"http_{r.status_code}", r.text[:200]
raise TicketAPIError(r.status_code, code, message)
class TicketClient:
"""Synchronous client. One instance per process; use as a context manager."""
def __init__(self, token: str, base_url: str = BASE_URL) -> None:
self._client = httpx.Client(
base_url=base_url,
headers={"Authorization": f"Bearer {token}", "Accept": "application/json"},
timeout=TIMEOUT,
follow_redirects=False,
)
def __enter__(self) -> "TicketClient":
return self
def __exit__(self, *exc) -> None:
self._client.close()
def _get(self, path: str, **params) -> httpx.Response:
r = self._client.get(path, params=params)
_raise_for_api(r)
return r
def get_ticket(self, ticket_id: int):
# In 01B.6 this becomes: return Ticket.model_validate(self._get(f"/tickets/{ticket_id}").json())
return self._get(f"/tickets/{ticket_id}").json()
def iter_tickets(self, status: str | None = None):
"""Cursor pagination: yield every ticket across pages."""
cursor = None
while True:
params = {"status": status} if status else {}
if cursor:
params["cursor"] = cursor
page = self._get("/tickets", **params).json()
yield from page["items"]
cursor = page.get("next_cursor")
if not cursor:
return
def create_ticket(self, payload: dict):
r = self._client.post("/tickets", json=payload)
_raise_for_api(r)
return r.json()
class AsyncTicketClient:
"""Async twin — same shape, await everywhere, aiter_tickets for pagination."""
def __init__(self, token: str, base_url: str = BASE_URL) -> None:
self._client = httpx.AsyncClient(
base_url=base_url,
headers={"Authorization": f"Bearer {token}", "Accept": "application/json"},
timeout=TIMEOUT,
follow_redirects=False,
)
async def __aenter__(self) -> "AsyncTicketClient":
return self
async def __aexit__(self, *exc) -> None:
await self._client.aclose()
async def _get(self, path: str, **params) -> httpx.Response:
r = await self._client.get(path, params=params)
_raise_for_api(r)
return r
async def get_ticket(self, ticket_id: int):
return (await self._get(f"/tickets/{ticket_id}")).json()
async def aiter_tickets(self, status: str | None = None):
cursor = None
while True:
params = {"status": status} if status else {}
if cursor:
params["cursor"] = cursor
page = (await self._get("/tickets", **params)).json()
for item in page["items"]:
yield item
cursor = page.get("next_cursor")
if not cursor:
return
async def create_ticket(self, payload: dict):
r = await self._client.post("/tickets", json=payload)
_raise_for_api(r)
return r.json()What this demonstrates, in one place: a configured client reused across calls (pooling), bearer auth without keys in code, a domain error type instead of raw httpx exceptions, status-check-before-parse, and cursor pagination as an iterator — sync iter_tickets() and async aiter_tickets() yield lazily so a million tickets never sit in memory. What it deliberately omits (later lessons add them): Pydantic decoding (01B.6), retries/backoff (01B.9), and structured logging (01B.10).
9.1 Preview: the same shape against a real LLM endpoint#
The exact same client pattern works unchanged against an LLM provider's raw HTTP API — this is what 03.1 Part 1 unpacks fully. Sketch only (illustrative — no key needed to read; the SDKs in Module 03 wrap this for you):
# Sketch: POST to the Responses API shape with raw httpx. Real use goes
# through the openai SDK (which uses httpx2 and wraps all of this) — see 03.1.
import os
import httpx
resp = httpx.post(
"https://api.openai.com/v1/responses",
headers={"Authorization": f"Bearer {os.environ['OPENAI_API_KEY']}"},
json={"model": "gpt-6-luna", "input": "Say hi in five words."},
timeout=httpx.Timeout(120.0, connect=5.0), # long read: generation is slow
)
resp.raise_for_status()
data = resp.json()
# The wire JSON has no top-level "output_text" — that's an SDK-side
# convenience property. On the wire, text lives under output[] -> message
# items -> content[] parts of type "output_text" (03.1 §5.1 walks the same
# shape; the SDKs join these parts for you).
text = "".join(
part["text"]
for item in data["output"] if item["type"] == "message"
for part in item["content"] if part["type"] == "output_text"
)
print(text)Note the timeout shape — short connect, long read — and that httpx2 would be the drop-in if your project standardises on the SDKs' fork (1.5). The wire details, headers and response shapes for all four providers are 03.1's job, not repeated here.
Failure gallery#
The failures this lesson exists to prevent, as symptom → cause → fix:
| Symptom | Cause | Fix |
|---|---|---|
httpx.ReadTimeout seconds into a call that "should be fast" |
The default 5 s timeout met a slow endpoint (or an LLM call) | Set httpx.Timeout(...) explicitly — short connect, generous read (3.3) |
json.decoder.JSONDecodeError out of .json() |
.json() ran on an HTML error page (WAF/proxy 502) with no status check |
raise_for_status() or a status_code check before parsing (4.3) |
Bursts of httpx.PoolTimeout while the network is fine |
Semaphore/concurrency exceeds limits.max_connections; requests queue past the pool timeout |
Align the semaphore and max_connections — it's a client-side queue, not the server (7.2) |
httpx.ResponseNotRead / StreamConsumed / StreamClosed |
Touched .content/.text, iterated twice, or read after close on a stream |
Buffer with r.read() inside the stream() block; iterate exactly once (5.1–5.2) |
Sockets pile up, too many open files, slow shutdown — often with no warning at all |
Client()/AsyncClient() never closed — no with, no aclose() |
with/async with, or close()/await aclose() in finally (3.1) |
?api_key=... visible in logs and tracebacks |
Query-string secrets copied into logged URLs; str(e)/exc.request.url dumps them verbatim |
Strip the query (safe_url), log type + status + sanitised URL (4.4) |
| Everything works but ~10× slower than it should | httpx.Client() built per request — a fresh TCP+TLS handshake every call, pool defeated |
One client per process, shared (2.1, 3.1) |
Three of them as the tracebacks surface in practice (line numbers and file names are examples):
ReadTimeout — the 5-second default meeting a slow endpoint:
Traceback (most recent call last):
File "report_job.py", line 18, in <module>
data = client.get("/reports/daily").json()
~~~~~~~~~~^^^^^^^^^^^^^^^^^^^
httpx.ReadTimeout: timed outJSONDecodeError — .json() on an HTML error page:
Traceback (most recent call last):
File "sync_tickets.py", line 23, in <module>
tickets = r.json()["items"]
~~~~~~^^
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)PoolTimeout — too much concurrency for the pool:
Traceback (most recent call last):
File "fanout.py", line 31, in <module>
asyncio.run(main())
~~~~~~~~~~~^^^^^^^^
httpx.PoolTimeout: timed outThe first two share a fix: the status check belongs before the parse, and the timeout belongs in the client config, not in hope. The third is the one people misdiagnose — PoolTimeout is your own concurrency queue overflowing, so adding retries or "a bigger timeout" makes it worse, not better.
Common misconceptions#
| Misconception | Reality |
|---|---|
"requests is abandoned/dead." |
It returned to the PSF and ships regularly (2.34.2, May 2026) — but it's still sync-only, which is why new async code uses httpx. |
"Top-level httpx.get() is fine for everything." |
Each call builds and destroys a client — new TCP+TLS handshake per request, no cookie/header reuse. Fine for scripts; use a Client for anything repeated. |
| "httpx follows redirects like requests does." | No — follow_redirects defaults to False. A 301 comes back as a 301 response you must handle — and raise_for_status() raises on it, since any non-2xx is an error to it. |
| "The default 5 s timeout is generous." | It's 5 s of inactivity per phase — fine for APIs, fatal for LLM calls. Set explicit timeouts; the read timeout is 'longest silence', not total time. |
| "A 404 means the request failed at the transport level." | No — you got a full response; HTTPStatusError only appears if you call raise_for_status(). |
"response.json() failing means httpx is broken." |
It means the body wasn't JSON — usually an HTML error page. Check status_code first. |
| "Streaming downloads need special code." | client.stream() + iter_bytes() writing to a file is the whole pattern; watch for missing Content-Length (chunked). |
"AsyncClient is a different API." |
Same methods, awaited — plus aiter_* streaming and async event hooks. |
"Creating an AsyncClient per task is harmless." |
Each owns a connection pool — one per task means one TLS handshake per request and pool exhaustion under load. One per process. |
"respx mocks all HTTP in my project." |
It patches httpx only — openai/anthropic SDK calls on httpx2 sail straight to the network. Use MockTransport of the right library. |
| "Retries belong in the HTTP client." | HTTPTransport(retries=N) only retries connect failures; status-based retry policy is application logic (01B.9). |
| "I must parse SSE by hand for LLM streams." | The provider SDKs parse it for you; hand-parsing is for your own endpoints or unusual providers — and 03.3 has the full parser. |
Key takeaways#
- Use
httpxfor your own HTTP code (0.28.1): sync and async in one API, strict timeouts by default, first-class streaming and testing.requestsis fine for sync scripts;aiohttpwhen you also need a server;httpx2when your project already rides on theopenai/anthropicSDKs. - One
Client/AsyncClientper process, as a context manager — pooling, cookies, defaults and TLS reuse all live there. Top-levelhttpx.get()is for one-offs only. follow_redirectsdefaults toFalse; set it deliberately.raise_for_status()raises on any non-2xx status — including an unfollowed redirect — so check status before.json().- Timeouts have four phases; the read timeout is longest-silence, not total time. Short connect, generous read, explicit pool — and never accept the 5 s default for slow APIs.
- The exception tree tells you the fix:
TimeoutException/NetworkError→ maybe retry;LocalProtocolError/InvalidURL→ your bug;HTTPStatusError→ look at the status;StreamError→ stream API misuse. - Stream big bodies and SSE with
client.stream()/iter_*/aiter_*; feed bytes to a parser that tolerates any chunking;[DONE]is just adata:payload. - Test without the network:
MockTransport(assert on the realRequest),respxforhttpxonly,http.serverfakes for real socket semantics,ASGITransportfor your FastAPI apps. - Ship a typed client: configured once, domain errors mapped, pagination as an iterator — the
aitoolkit/http.pypattern scales to every API you'll call.
Where you'll use this in the AI path#
- 03.1 §4.5 — The
httpx2switch: why the SDKs moved offhttpx, and the client/mocking consequences. - 03.3 — Streaming responses: provider SSE streams in full — §2.5's parser is the production version of this lesson's small one.
- 03.8 — Errors, rate limits, timeouts: transport failures and timeout selection for LLM calls.
- 03.9 — Async, concurrency and batch: the four async SDK clients, semaphore-vs-pool interaction, batch APIs (polled over HTTP).
- 03.10 — Debugging and testing: wire logging via event hooks, the
respxtrap, record/replay. - 05.3 §3.1 —
httpxfor crawling: the same client fetching and parsing web pages at scale. - 08E.1 §2.6 — MCP transports: Streamable HTTP is POST + optional SSE — exactly the patterns here.
- 09.3 — Image generation: submit → poll → download binary results over HTTP.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| HTTP client | Library that builds, sends and receives HTTP requests/responses |
httpx |
The modern Python HTTP client: sync + async, HTTP/2, timeouts, streaming |
httpx2 |
Pydantic's maintained fork of httpx, used by openai 3.x and anthropic 2.x (and, from 3.0.0, by google-genai) |
Client / AsyncClient |
Reusable httpx objects owning a connection pool and defaults |
| Connection pool | Cache of open keep-alive connections reused across requests |
| Keep-alive | Reusing one TCP connection for multiple HTTP requests |
httpx.Timeout |
Four-phase timeout config: connect, read, write, pool |
httpx.Limits |
Pool sizing: max_connections, max_keepalive_connections, keepalive_expiry |
PoolTimeout |
Error when no pooled connection frees up within the pool timeout |
trust_env |
Client flag honouring proxy/SSL/netrc environment variables |
| Event hook | Callable fired per request/response (logging, tracing, metrics) |
| Transport | The layer under the client API: HTTPTransport, MockTransport, ASGITransport... |
MockTransport |
httpx transport answering requests with a Python handler — the test fake |
respx |
pytest mocking library that patches httpx (not httpx2) |
raise_for_status() |
Response method raising HTTPStatusError on any non-2xx status |
iter_bytes/aiter_lines |
Streaming readers over a response body, sync/async |
| Server-Sent Events (SSE) | text/event-stream format: data: lines, blank-line dispatch, : comments |
| Multipart form | multipart/form-data body for file uploads (files=) |
| Cursor pagination | Page-at-a-time API style where next_cursor drives the next request |
| Content negotiation | Accept/Accept-Encoding request headers (and Content-Type/Content-Encoding/Vary responses) by which client and server agree on a representation |
All terms are also collected in the glossary.
Exercises#
- Top-level vs client (2.1): Time (conceptually) why
httpx.get(url)in a loop of 100 is slower than oneClient. Which httpx feature makes the difference? - Params and redirects (2.4):
client.get("/old")returns 301. Write the two ways to end up at the final page, and explain whatresponse.historycontains in each. - Timeouts (3.3): A batch job calls an endpoint that takes up to 90 s to answer without streaming. Write the
httpx.Timeoutyou'd use and justify each phase. - Exceptions (4.2): Your code catches
httpx.HTTPErroraroundclient.post(...). Which of these does it not catch:ConnectTimeout,HTTPStatusError,InvalidURL,json.JSONDecodeError? Fix theexceptclauses. - Streaming (5.1): Convert the download snippet in 6.2 to
AsyncClient(aiter_bytes,async with). What must change about closing? - SSE parser (5.3): Feed
sse_eventsa fixture where one event'sdata:spans three lines and one event hasdata:with no space after the colon (data:x). Predict the output, then run it. - PoolTimeout (7.2): You set
asyncio.Semaphore(50)andlimits=httpx.Limits(max_connections=10). What happens, and what's the fix? - MockTransport (8.1): Write a handler that returns 429 on the first call and 200 on the second, and show how you'd assert both requests carried the same
Idempotency-Keyheader. - aitoolkit client (9): Add a
delete_ticket(ticket_id)method to both client classes, mapping 404 to returningFalseinstead of raising. - Encoding (2.2): A legacy endpoint serves Shift-JIS with no charset header. Show the client configuration that decodes it correctly.
- httpx2 decision (1.5): Your project depends on
openai3.x and you need a plainGEThelper. Argue forhttpxvshttpx2in two sentences each, then pick one and say why. - Content negotiation (2.7): Your ticket export endpoint serves
text/csvorapplication/jsonand honoursAcceptquality values. Write the headers to prefer CSV but accept JSON, then explain what httpx puts onAccept-Encodingautomatically and why you shouldn't narrow it carelessly. - Event hooks (3.7): Write an async response hook that records
response.status_codeandresponse.elapsedinto a list, and explain why it must beasync def.
Solutions
- Each top-level call constructs a new
Client, does the request and closes it — a fresh TCP+TLS handshake per call, no keep-alive reuse, no shared cookie/header state. AClientpools connections so requests 2..100 reuse the handshake. (Connection pooling, §3.1.) client.get("/old", follow_redirects=True)follows automatically —response.historyholds the 301 response(s) andresponse.urlis the final URL. Or inspectr = client.get("/old")(a 301), readr.headers["location"]/r.next_request, and issue the second request yourself —historystays empty because you made two requests, not a redirect chain.httpx.Timeout(120.0, connect=5.0)— connect 5 s (fast fail on network trouble), read/write/pool 120 s (the read timeout must outlast the longest silence, here the whole 90 s generation). Pool can stay default or be set explicitly; total time isn't bounded by any single timeout — that's what a deadline is for (01B.9).ConnectTimeoutandHTTPStatusErrorareHTTPErrorsubclasses — caught.InvalidURLis a plainException(notHTTPError) — escapes.json.JSONDecodeErroris aValueError— escapes. Fix:except (httpx.HTTPError, httpx.InvalidURL)plus a separateexcept ValueErroraround.json()if you parse.async with httpx.AsyncClient(...) as client: async with client.stream("GET", url) as r: async for chunk in r.aiter_bytes(): ...— the nested async context managers close the response then the client; no manualaclose()needed.- Three
data:lines join with\ninto one event's payload;data:x(no space) still parses because the parser strips at most one optional leading space — both forms yield the same value. Run it to confirm; the fixture in 5.3 already exercises multi-linedata:. - 50 tasks compete for 10 connections, so about 40 wait for a free one. Any task that waits longer than the 5 s default pool timeout (easily the case when requests take a few seconds each) raises
PoolTimeout, so you see bursts of them. Fix: raisemax_connections/max_keepalive_connectionsto ≥50, or lower the semaphore to ≤10. calls = []in the handler; appendrequest.headers.get("idempotency-key")per call; returnhttpx.Response(429, ...)whenlen(calls) == 1elsehttpx.Response(200, json={...}). Assertcalls == [key, key]after the client retries (with 01B.9's retry or a manual second call).def delete_ticket(self, ticket_id): r = self._client.delete(f"/tickets/{ticket_id}"); if r.status_code == 404: return False; _raise_for_api(r); return True— the async twin is identical withawait self._client.delete(...).client = httpx.Client(default_encoding="shift-jis")— used whenever the response lacks a charset; per-response override isr.encoding = "shift-jis"before reading.text.httpx: larger ecosystem,respxcompatibility, most examples assume it.httpx2: consistency with the SDKs' HTTP stack, OS trust store, Pydantic stewardship. Pickhttpxunless the project standardises onhttpx2throughout — mixing is legal but doubles the mocking surface.headers={"Accept": "text/csv;q=1.0, application/json;q=0.5"}on the client or per request — theqvalues rank CSV first. httpx automatically sendsAccept-Encoding: gzip, deflate(plusbr/zstdwith the[brotli]/[zstd]extras) and decodes matchingContent-Encodingresponses for you. Don't narrow it carelessly: aContent-Encodingwith no installed decoder is silently passed through as still-compressed bytes, so only advertise encodings you can decode.async def hook(response): seen.append((response.status_code, response.elapsed))registered underevent_hooks={"response": [hook]}; it must be async becauseAsyncClientawaits hooks — a sync function raises when the first response arrives.
Check yourself#
- Why does
httpx.get(url)in a loop underperformwith httpx.Client() as c: c.get(url)?Each top-level call creates and destroys aClient: a fresh TCP+TLS handshake per request, no keep-alive reuse, no shared defaults. AClientpools connections. - What's the default for
follow_redirects, and how does that differ fromrequests?False— redirects come back as responses you handle.requestsfollows redirects by default. - Name the four timeout phases and what each guards.
connect(TCP/TLS handshake),read(gap between received chunks — not total time),write(sending the body),pool(waiting for a pooled connection). - Why is httpx's default timeout a trap for LLM calls specifically?LLM calls are slow: non-streaming answers take many seconds of silence, streams have long gaps. The 5 s default fires
ReadTimeoutmid-generation. Use long read timeouts (03.8 has the per-provider values). - Which exceptions does
except httpx.HTTPErrorcatch, and which common errors escape it?It catchesRequestError(all transport/timeout/decoding/redirect errors) andHTTPStatusError. It does not catchInvalidURL,CookieConflict,StreamError, or non-httpx errors likejson.JSONDecodeError. - What does
raise_for_status()do on a 302? On a 503?Both raiseHTTPStatusError—raise_for_status()returnsselfonly for 2xx, so a 302 raises too (withfollow_redirects=False, the default, an unfollowed redirect is a non-2xx response; checkis_redirectfirst if redirects are legitimate). On 503 it raises as well, carrying.responseand.request. - Why check
status_codebefore callingresponse.json()?Error pages (HTML from a WAF/proxy, or a JSON error object) aren't the data you expect —.json()givesJSONDecodeErroror a misleading payload. Status first, parse second. - What's the difference between
iter_bytes()anditer_raw()?iter_bytesyields content-decoded bytes (gzip/br undone);iter_rawyields the still-encoded wire bytes (de-chunked but not de-compressed). - How do you make an SSE parser robust to arbitrary network chunking?Incremental UTF-8 decoding (
codecs.getincrementaldecoder) plus a line buffer that only emits complete\n-terminated lines — any chunk boundary works. - What does
httpx.MockTransport's handler receive and return?It receives the realhttpx.Request(method, URL, headers, body) and must return anhttpx.Response— status, headers, content — which the client then processes normally. - Why can't
respxmockopenai/anthropicSDK calls anymore?Those SDKs depend onhttpx2, a different package with different classes;respxpatcheshttpx's transport only, so the "mock" never intercepts and the request goes to the real network. - What two things does a shared
AsyncClientgive you that per-request clients don't?Connection reuse (no per-request handshake) and shared state: cookies, default headers/params/auth, proxy/TLS/timeout config applied uniformly. - When would you choose
httpx2overhttpxfor your own code?When the project already depends onhttpx2via theopenai/anthropicSDKs and you want one HTTP stack — same API shape, Pydantic-maintained, OS trust store. - What's the symptom of a semaphore larger than the connection pool, and where does it surface?Excess tasks queue for a pooled connection and hit the pool timeout →
PoolTimeoutbursts. Raisemax_connections/max_keepalive_connectionsor lower the semaphore. - What
Accept-Encodingdoes httpx send by default, and what happens if the server answers with an encoding httpx has no decoder for?Accept-Encoding: gzip, deflate— plusbr/zstdwhen the[brotli]/[zstd]extras are installed. An encoding with no installed decoder is silently skipped, so the body comes back still-compressed; that's why you should only narrow the header to encodings you can decode.
Further resources#
- httpx documentation — the authoritative reference: QuickStart, Clients, Timeouts, Transports, Exceptions, API reference.
- httpx2 documentation and repository — Pydantic's fork used by the provider SDKs.
- requests documentation — for comparing the incumbent's model.
- aiohttp documentation — the async client+server alternative.
- httpx-sse — SSE helpers for httpx (beta; pin it).
- respx — httpx mocking for tests.
- MDN HTTP overview — the protocol itself, when you need the wire-level view (00.6 covers it too).
- Module 03 lessons — 03.1 (provider APIs and the httpx2 switch), 03.3 (streaming and SSE), 03.8 (errors and retries), 03.9 (async and batch), 03.10 (testing LLM code).
← 01B.4 — Concurrency Patterns for I/O-Heavy Work | Module 01B overview | 01B.6 — Data Validation with Pydantic →