Pirate Cheat Sheets
Sync + async HTTP client with HTTP/2

httpx
cheat sheet

The httpx library at a glance: clients, async, timeouts, limits, transports, streaming, auth, testing with mock transports, and the CLI.

Version
v0.28.1
Snippets
85
Sections
12

Version notes · httpx 0.28.1

  • 0.28 removed proxies=: use proxy="http://…" or mounts={…}.
  • 0.28 removed the app= shortcut: use transport=httpx.ASGITransport(app=app) (or WSGITransport).
  • 0.28 deprecates verify="path.pem" and cert=: pass an ssl.SSLContext to verify= instead.
  • Unlike requests: a 5 s default timeout, and redirects are not followed unless follow_redirects=True.

A requests-style HTTP client with both sync and async APIs, optional HTTP/2, strict timeouts, pluggable transports and a command-line client.

Used byFastAPI TestClientOpenAI SDKAnthropic SDKStarlette

Sync & async

Client and AsyncClient, same API

HTTP/2

with `httpx[http2]`

Timeouts on

5 s by default, everywhere

Transports

mock, ASGI, WSGI, retries

Quick start

uv add httpxuvx --from "httpx[cli]" httpx https://httpbin.org/jsonuv run python -c "import httpx; print(httpx.get('https://httpbin.org/get').json())"

Install

  • Core client
  • HTTP/2 support (h2)
  • SOCKS proxies
  • Brotli / Zstandard decoding
  • The httpx command

Command line

  • GET, pretty-printed
  • POST JSON
  • Query param + header
  • Show the request too
  • Save to a file
  • GET (5 s timeout)
  • POST JSON
  • Form-encoded body
  • Multipart upload
  • Raw body (content=, not data=)
  • Query string
  • Headers
  • Follow redirects
  • Any method

Like requests, the top-level helpers open a fresh connection every call. For more than one request, use a Client.

  • Connection pool, closed on exit
  • Relative URLs: client.get("/users")
  • Default headers
  • Default query params
  • Default timeout
  • Follow redirects for every call
  • HTTP/2 (needs httpx[http2])
  • Change defaults later
  • Build without sending
  • Send a built request
  • Async client (same options)
  • Await every request
  • Many requests at once
  • Async streaming
  • Async chunks (aiter_lines, aiter_text)
  • Read a streamed body
  • Close without async with

fetch_all.py

import asyncio, httpxasync def main(urls):    limits = httpx.Limits(        max_connections=10)    async with httpx.AsyncClient(            limits=limits) as c:        rs = await asyncio.gather(            *(c.get(u) for u in urls))    return [r.status_code for r in rs]asyncio.run(main(urls))

Works with asyncio and trio. Create one AsyncClient and reuse it: a client per request throws the pool away.

  • 200, 404…
  • 2xx (is_error, is_redirect too)
  • Raises on 4xx / 5xx, else returns r
  • Parse JSON
  • Decoded text
  • Raw bytes
  • Case-insensitive headers
  • HTTP/1.1 or HTTP/2
  • Time until the response closed
  • Redirects that led here
  • The redirect not taken (if not following)
  • What was sent

Timeouts

  • All four timeouts (default 5 s)
  • Override one of them
  • connect · read · write · pool
  • Disable timeouts

Pool & retries

  • Pool size (default 100)
  • Idle connections kept (default 20)
  • Retry failed connects (not responses)
  • Use them

retries= only retries ConnectError / ConnectTimeout. For 429 / 5xx retries, wrap calls with a library such as tenacity or stamina.

  • Stream without a client
  • Stream with a client
  • Decoded chunks
  • Line by line (NDJSON, SSE)
  • Undecoded bytes from the wire
  • Progress counter
  • Chunked upload from a generator
  • Basic auth (or httpx.BasicAuth)
  • Digest auth
  • Credentials from ~/.netrc
  • Custom: auth_flow yields requests
  • One proxy for everything
  • Proxy per scheme / host
  • Custom CA
  • No TLS checks (testing only)
  • Ignore HTTPS_PROXY, SSL_CERT_FILE, netrc
  • Base of request + status errors
  • From raise_for_status()
  • Failed status
  • Network-level failure
  • Which request failed
  • Any timeout (ConnectTimeout, ReadTimeout…)
  • DNS / refused connection
  • Redirect loop (max 20)
  • Run before each request
  • Run after each response
  • Raise everywhere
  • With AsyncClient, hooks are async

In a response hook the body is not read yet: call r.read() before using r.text or r.json().

  • Fake server function
  • No network at all
  • Call a FastAPI / Starlette app
  • Call a Flask / Django app
requestshttpx
  • httpx.Client()
  • httpx.post(url, content=b"raw")
  • httpx.get(url, follow_redirects=True)
  • r.is_success
  • r.iter_bytes(1024)
  • httpx.stream("GET", url)
  • proxy=p
  • httpx.Client(mounts={"https://": httpx.HTTPTransport()})
  • httpx.HTTPError