Chapter 2 · API Design and API Clients
Professional API Clients with httpx and asyncio
- Page 7 of 22
- 26 min read
Almost every AI product is a client before it is anything else. A RAG service calls an embedding API and a vector database, an agent calls ten tools in a row, a data pipeline pulls thousands of records from a partner API, and every LLM request is an HTTP call to a provider. In the beginner tutorial you used requests for one call at a time. This page is about the client code that runs in production: one shared connection pool, timeouts on every call, retries that respect the server, many requests in flight at once with asyncio, streamed answers, typed results, tests that never touch the network, and logs that never leak a key.
The tool is httpx: a requests-like API that also speaks async, HTTP/2 and streaming. Everything runs against the BitByte Practice API on http://localhost:8800, so start it in a second terminal if it is not already running (fastapi run practice_api.py --port 8800).
What you will learn
- How httpx differs from
requests, and what httpx2 is and why the OpenAI and Anthropic SDKs moved to it. - Reusing one
httpx.Clientfor connection pooling, with base URL, headers, limits and explicit timeouts. - Retries with exponential backoff, jitter and
Retry-After, and a pagination helper. asynciofundamentals,AsyncClient,gatherwith a semaphore, deadlines, and consuming an SSE stream.- A typed client with Pydantic, tested with respx and
MockTransport, safe logging, and packaging it as a library.
Set up the project
mkdir -p ~/projects/api-clients
cd ~/projects/api-clients
uv init --bare
uv add -q httpx pydantic
uv add -q --dev pytest pytest-asyncio respx
# with pip instead:
# python -m venv .venv && source .venv/bin/activate
# pip install -q httpx pydantic pytest pytest-asyncio respx
lsInitialized project `api-clients`
pyproject.toml
uv.lockThe Python snippets on this page continue one another, like cells in a notebook. Run them in uv run python (or Jupyter) from this folder, or paste them into a file and run it with uv run python file.py.
requests, httpx and httpx2
A first call looks exactly like requests:
import httpx
BASE_URL = "http://localhost:8800"
response = httpx.get(f"{BASE_URL}/v1/courses", params={"level": "advanced"})
print(response.status_code, response.http_version)
print(response.url)
print([course["title"] for course in response.json()["items"]])200 HTTP/1.1
http://localhost:8800/v1/courses?level=advanced
['RAG Systems', 'AI Agents', 'LLMOps']The differences matter once code runs unattended:
requests 2.34 | httpx 0.28 / httpx2 2.x | |
|---|---|---|
| Default timeout | none: a hung server hangs your program forever | 5 seconds for connect, read, write and pool |
| Redirects | followed automatically | not followed unless follow_redirects=True |
| Async | no | httpx.AsyncClient with the same methods |
| HTTP/2 | no | optional: pip install "httpx[http2]", Client(http2=True) |
| Streaming | stream=True + iter_lines() | with client.stream(...) + iter_lines() / aiter_lines() |
| Test hook | third-party (responses) | built-in MockTransport, plus respx |
What httpx2 is
httpx's last release, 0.28.1, came out in December 2024, and its long-promised 1.0 has not appeared. In May 2026 Pydantic started httpx2, a maintained fork of httpx 0.28.1 with the same API under a new import name. The OpenAI SDK (3.x) and the Anthropic SDK (1.x) now depend on httpx2, and Starlette's TestClient prefers it. The code on this page uses import httpx, because that is what most documentation and existing code show; switching is one line:
import httpx2
print(httpx2.Client is httpx.Client) # two separate libraries
with httpx2.Client(base_url=BASE_URL) as other:
print(other.get("/health").json())
print(other.headers["user-agent"].split("/")[0])False
{'status': 'ok'}
python-httpx2- To move a file over, write
import httpx2 as httpx; the classes, methods and exceptions are the same. Objects from the two libraries do not mix (anhttpx.Responseis not anhttpx2.Response). - httpx2 verifies TLS against the operating system's certificate store (via
truststore) instead of thecertifibundle. Slim Docker images need theca-certificatespackage (Debianpython:*-slimimages have it). - Tools built for httpx, such as respx below, patch
httpxonly. For a new application, httpx2 is the safer long-term choice; for a library, accept either by letting callers pass the client in.
One client, many requests: connection pooling
The function httpx.get() opens a new connection, sends one request and closes it. Opening a connection costs a TCP handshake and, for HTTPS, a TLS handshake: easily 50 to 300 ms to a provider on another continent, before the first byte of your request. A Client keeps connections open and reuses them (HTTP keep-alive). httpx can report what happens on the wire through the trace extension, so count the new connections:
def count_connections(client, n):
opened = []
def trace(event, info):
if event == "connection.connect_tcp.complete":
opened.append(event)
for _ in range(n):
client.get(f"{BASE_URL}/health", extensions={"trace": trace})
return len(opened)
with httpx.Client() as shared:
print("one shared client: ", count_connections(shared, 5), "connection(s) for 5 requests")
total = 0
for _ in range(5):
with httpx.Client() as throwaway:
total += count_connections(throwaway, 1)
print("a client per request:", total, "connection(s) for 5 requests")one shared client: 1 connection(s) for 5 requests
a client per request: 5 connection(s) for 5 requestsSo create one client per upstream service when your program starts, use it everywhere, and close it when the program ends (in FastAPI that is the lifespan, on the next pages). Configure it once:
client = httpx.Client(
base_url=BASE_URL,
headers={"User-Agent": "bitbyte-notebook/1.0", "Accept": "application/json"},
timeout=httpx.Timeout(10.0, connect=3.0),
limits=httpx.Limits(max_connections=20, max_keepalive_connections=10),
)
echo = client.get("/v1/echo", params={"q": "vector databases", "k": 3}).json()
print(echo["query"])
print(echo["headers"])
print(client.timeout){'q': 'vector databases', 'k': '3'}
{'user-agent': 'bitbyte-notebook/1.0', 'accept': 'application/json'}
Timeout(connect=3.0, read=10.0, write=10.0, pool=10.0)base_urllets every call use a path, so moving from the practice API to staging is one setting.paramsare URL-encoded for you: the space and the number arrived intact.limitscaps how many connections the pool opens. If all 20 are busy, the next request waits for a free one, up to the pool timeout.
Timeouts and errors
httpx has four timeouts, and each guards a different failure:
| Timeout | Limits the time to… | Typical value |
|---|---|---|
connect | open the TCP/TLS connection | 2–5 s: a server that cannot accept a connection is down |
read | wait for the next chunk of the response | 10–30 s; LLM calls without streaming may need 60–120 s |
write | send a chunk of the request body | like read; matters for uploads |
pool | wait for a free connection from the pool | a few seconds; if this fires, your pool is too small or something leaks |
The read timeout is per chunk, not for the whole response: a stream that sends a token every second never trips a 10-second read timeout, even if it runs for five minutes. For an overall deadline, use asyncio.timeout() (later on this page). The exceptions form a tree, so you can catch as broadly or narrowly as you need:
httpx.HTTPError
├── httpx.HTTPStatusError raise_for_status() on a 4xx/5xx response
└── httpx.RequestError no usable response at all
└── httpx.TransportError
├── httpx.TimeoutException
│ ├── ConnectTimeout ReadTimeout WriteTimeout PoolTimeout
└── httpx.NetworkError
├── ConnectError ReadError WriteError CloseErrorTrigger three of them on purpose: a slow endpoint with a short read timeout, a port where nothing is listening, and a missing course:
def try_call(label, func):
try:
response = func()
response.raise_for_status()
print(f"{label}: {response.status_code}")
except httpx.HTTPStatusError as exc:
print(f"{label}: HTTPStatusError {exc.response.status_code} {exc.response.json()['detail']!r}")
except httpx.TimeoutException as exc:
print(f"{label}: {type(exc).__name__}")
except httpx.RequestError as exc:
print(f"{label}: {type(exc).__name__} {exc}")
try_call("slow", lambda: client.get("/v1/slow", params={"seconds": 2}, timeout=httpx.Timeout(5.0, read=0.5)))
try_call("down", lambda: client.get("http://localhost:8001/health"))
try_call("missing", lambda: client.get("/v1/courses/99"))
try_call("ok", lambda: client.get("/v1/courses/8"))slow: ReadTimeout
down: ConnectError [Errno 111] Connection refused
missing: HTTPStatusError 404 'Course 99 not found'
ok: 200Notice that a per-request timeout= overrides the client's, and that an absolute URL overrides base_url. Catch HTTPStatusError and RequestError separately: the first means the server answered (you can read its error body), the second means you never got an answer (retry might help).
Retries, backoff and rate limits
Networks drop packets, load balancers restart, providers return 503 under load and 429 when you exceed your quota. A production client retries some failures, waits longer each time, and gives up in time. The rules:
- Retry connection errors, timeouts and the statuses
429,502,503,504. Never retry400,401,403,404or422: the same request will fail the same way. - Only retry idempotent requests (GET, PUT, DELETE) blindly. A
POSTthat timed out may already have charged a card or started an LLM job; retry it only with an idempotency key (Designing Robust APIs: Pagination, Rate Limits, Retries and Versioning). - Back off exponentially with jitter: wait about
base × 2^attempt, randomised, so a thousand clients that failed together do not retry together. - Respect
Retry-After, and give up if it asks you to wait longer than your caller can afford.
httpx.HTTPTransport(retries=3) exists, but it retries only failed connections (ConnectError, ConnectTimeout), never status codes. Status-aware retries are your code:
# file: retrying.py
"""Status-aware retries with exponential backoff, full jitter and Retry-After."""
import random
import time
import httpx
RETRY_STATUSES = {429, 502, 503, 504}
RETRY_ERRORS = (httpx.ConnectError, httpx.ConnectTimeout, httpx.ReadTimeout)
def retry_after_seconds(response):
"""Seconds from a numeric Retry-After header, or None."""
value = response.headers.get("Retry-After", "")
return float(value) if value.isdigit() else None
def request_with_retries(client, method, url, *, attempts=4, base_delay=0.2, max_wait=5.0,
log=print, **kwargs):
for attempt in range(1, attempts + 1):
response = None
try:
response = client.request(method, url, **kwargs)
if response.status_code not in RETRY_STATUSES:
return response
reason = f"HTTP {response.status_code}"
except RETRY_ERRORS as exc:
reason = type(exc).__name__
if attempt == attempts:
raise
if attempt == attempts:
return response
wait = retry_after_seconds(response) if response is not None else None
if wait is None:
wait = random.uniform(0, base_delay * 2 ** attempt) # "full jitter"
if wait > max_wait:
log(f" attempt {attempt}: {reason}, server asks for {wait:.0f} s, giving up")
return response
log(f" attempt {attempt}: {reason}, retrying")
time.sleep(wait)from retrying import request_with_retries
print("flaky endpoint:")
r = request_with_retries(client, "GET", "/v1/flaky", params={"key": "p07-demo", "fail_times": 2})
print(" ", r.status_code, r.json())
print("rate-limited endpoint:")
for call in range(4):
r = request_with_retries(client, "GET", "/v1/limited", headers={"X-Client-Id": "p07-notebook"})
print(" ", r.status_code, r.json(), r.headers.get("Retry-After"))flaky endpoint:
attempt 1: HTTP 503, retrying
attempt 2: HTTP 503, retrying
200 {'ok': True, 'attempt': 3}
rate-limited endpoint:
200 {'ok': True, 'remaining': 2} None
200 {'ok': True, 'remaining': 1} None
200 {'ok': True, 'remaining': 0} None
attempt 1: HTTP 429, server asks for 10 s, giving up
429 {'detail': 'Too many requests'} 10The flaky endpoint failed twice and succeeded on the third attempt. The rate-limited endpoint allows three calls per ten seconds; the fourth got 429 with Retry-After: 10, which is more than this caller's max_wait, so the function returned the 429 at once instead of sleeping. That is a retry budget: a user waiting for a chatbot answer cannot wait ten seconds plus three retries, and failing fast with a clear message is better. A nightly batch job could afford a larger max_wait.
Retry-Aftermay also be an HTTP date (Wed, 21 Oct 2026 07:28:00 GMT);email.utils.parsedate_to_datetimeparses it. Libraries such as tenacity or stamina package this logic with decorators; writing it once yourself is how you learn what they should be configured to do.
Pagination helper
Listing endpoints return one page at a time. Hide the page loop in a generator so callers just iterate:
def iter_courses(client, level=None, per_page=4):
"""Yield every course, following next_page until it is None."""
page = 1
while page is not None:
params = {"page": page, "per_page": per_page}
if level:
params["level"] = level
response = client.get("/v1/courses", params=params)
response.raise_for_status()
body = response.json()
print(f" fetched page {body['page']} ({len(body['items'])} items)")
yield from body["items"]
page = body["next_page"]
titles = [course["title"] for course in iter_courses(client)]
print(len(titles), "courses; last:", titles[-1])
first_two = []
for course in iter_courses(client, per_page=2):
first_two.append(course["id"])
if len(first_two) == 2:
break
print(first_two) fetched page 1 (4 items)
fetched page 2 (4 items)
fetched page 3 (2 items)
10 courses; last: LLMOps
fetched page 1 (2 items)
[1, 2]Because it is a generator, the second loop fetched only one page: it stopped asking as soon as the caller stopped iterating. For cursor-based APIs (next_cursor instead of next_page) the shape is the same.
A typed client with Pydantic
Scattering response.json()["items"][0]["title"] across a codebase means that when the upstream API changes a field, you find out from a KeyError deep inside your business logic. A client class puts all knowledge of one API in one place, validates every response with Pydantic at the boundary, and turns HTTP failures into your own exceptions. Save it as a module:
# file: bitbyte_client.py
"""A small typed client for the BitByte Practice API."""
from collections.abc import Iterator
import httpx
from pydantic import BaseModel, ValidationError
class Course(BaseModel):
id: int
title: str
level: str
hours: int
rating: float
class CoursePage(BaseModel):
page: int
total: int
next_page: int | None
items: list[Course]
class Weather(BaseModel):
city: str
temp_c: float
humidity: int
condition: str
class BitByteError(Exception):
"""Base class for every error this client raises."""
class NotFound(BitByteError):
pass
class UpstreamError(BitByteError):
"""The API failed, or answered with data we cannot use."""
class BitByteClient:
def __init__(self, base_url: str, *, timeout: float = 10.0,
transport: httpx.BaseTransport | None = None) -> None:
self._http = httpx.Client(
base_url=base_url,
timeout=httpx.Timeout(timeout, connect=3.0),
headers={"User-Agent": "bitbyte-client/0.1"},
transport=transport,
)
def __enter__(self) -> "BitByteClient":
return self
def __exit__(self, *exc_info) -> None:
self.close()
def close(self) -> None:
self._http.close()
def _get(self, path: str, **params) -> dict:
try:
response = self._http.get(path, params=params)
except httpx.RequestError as exc:
raise UpstreamError(f"GET {path} failed: {type(exc).__name__}") from exc
if response.status_code == 404:
raise NotFound(response.json().get("detail", path))
if response.is_error:
raise UpstreamError(f"GET {path} returned {response.status_code}")
return response.json()
def get_course(self, course_id: int) -> Course:
return self._parse(Course, self._get(f"/v1/courses/{course_id}"))
def list_courses(self, *, level: str | None = None, page: int = 1, per_page: int = 5) -> CoursePage:
params = {"page": page, "per_page": per_page}
if level:
params["level"] = level
return self._parse(CoursePage, self._get("/v1/courses", **params))
def iter_courses(self, *, level: str | None = None) -> Iterator[Course]:
page: int | None = 1
while page is not None:
result = self.list_courses(level=level, page=page, per_page=20)
yield from result.items
page = result.next_page
def weather(self, city: str) -> Weather:
return self._parse(Weather, self._get("/v1/weather", city=city))
@staticmethod
def _parse(model, data):
try:
return model.model_validate(data)
except ValidationError as exc:
raise UpstreamError(f"unexpected {model.__name__} payload: {exc.error_count()} error(s)") from excUse it like any library. Notice that callers now get attributes with types (course.rating is a float, your editor can autocomplete it), and only the client's own exceptions:
from bitbyte_client import BitByteClient, NotFound
with BitByteClient(BASE_URL) as bitbyte:
course = bitbyte.get_course(8)
print(course)
print(sum(c.hours for c in bitbyte.iter_courses(level="beginner")), "hours of beginner courses")
print(bitbyte.weather("Sylhet").model_dump())
try:
bitbyte.get_course(99)
except NotFound as exc:
print("NotFound:", exc)id=8 title='RAG Systems' level='advanced' hours=10 rating=4.9
42 hours of beginner courses
{'city': 'Sylhet', 'temp_c': 27.4, 'humidity': 85, 'condition': 'Rain'}
NotFound: Course 99 not foundThe transport argument looks unused for now. It is the seam for testing, which you will use below.
asyncio in one section
Most of an API client's life is waiting: for the network, for the server, for the model to generate tokens. A synchronous program waits for one response before sending the next request. asyncio lets one thread start many requests and work on whichever answers first. The vocabulary:
| Term | Meaning |
|---|---|
| coroutine function | async def f(): .... Calling f() runs nothing yet; it returns a coroutine object. |
await | "run this and pause me until it finishes; meanwhile the event loop may run other tasks". Only allowed inside async def. |
| event loop | the scheduler that switches between tasks whenever one awaits I/O. asyncio.run(main()) starts one, runs main(), and closes it. |
| task | a coroutine scheduled to run concurrently: asyncio.create_task(), asyncio.gather() or a TaskGroup. |
httpx.AsyncClient has the same methods as Client, but they are coroutines. Fetch four slow responses (half a second each) one after another, then all at once:
import asyncio
import time
async def fetch_slow(client, seconds):
response = await client.get("/v1/slow", params={"seconds": seconds})
return response.json()["waited_seconds"]
async def compare():
async with httpx.AsyncClient(base_url=BASE_URL, timeout=10.0) as aclient:
start = time.perf_counter()
for _ in range(4):
await fetch_slow(aclient, 0.5)
sequential = time.perf_counter() - start
start = time.perf_counter()
results = await asyncio.gather(*(fetch_slow(aclient, 0.5) for _ in range(4)))
concurrent = time.perf_counter() - start
print("results:", results)
print("sequential took at least 2 s:", sequential >= 2.0)
print("concurrent took under 1 s: ", concurrent < 1.0)
asyncio.run(compare())results: [0.5, 0.5, 0.5, 0.5]
sequential took at least 2 s: True
concurrent took under 1 s: Truegather started all four coroutines, and while each awaited its response the loop ran the others, so four waits of 0.5 s overlapped into about 0.5 s. That is the whole trick, and its limits follow from it:
- asyncio helps with waiting (I/O). It does not make CPU work (tokenising, NumPy, model inference) faster; that needs threads or processes.
- One blocking call inside a coroutine (
time.sleep,requests.get, a sync database driver) freezes every task. Insideasync def, use only awaitable I/O:await asyncio.sleep(),AsyncClient, async drivers. - In Jupyter a loop is already running, so write
await compare()in a cell instead ofasyncio.run(compare()).
Many requests, safely: a semaphore and a deadline
"Fire everything at once" is how you get rate-limited or banned. If you need 500 embeddings and the provider allows 10 concurrent requests, you cap your concurrency. An asyncio.Semaphore(n) lets at most n tasks inside a block at a time. The code below fetches 13 resources with at most 3 in flight, records the peak, and collects failures instead of crashing on the first one:
async def fetch_all(paths, limit=3):
semaphore = asyncio.Semaphore(limit)
in_flight = peak = 0
async def fetch(aclient, path):
nonlocal in_flight, peak
async with semaphore: # waits here while 3 are running
in_flight += 1
peak = max(peak, in_flight)
try:
response = await aclient.get(path)
response.raise_for_status()
return response.json()
finally:
in_flight -= 1
async with httpx.AsyncClient(base_url=BASE_URL, timeout=10.0) as aclient:
results = await asyncio.gather(*(fetch(aclient, p) for p in paths), return_exceptions=True)
return results, peak
cities = ["Dhaka", "Chattogram", "Sylhet", "Khulna", "Rajshahi"]
paths = [f"/v1/weather?city={c}" for c in cities] + [f"/v1/courses/{i}" for i in (1, 2, 3, 6, 7, 9, 10, 99)]
results, peak = asyncio.run(fetch_all(paths))
ok = [r for r in results if not isinstance(r, Exception)]
failed = [(p, type(r).__name__) for p, r in zip(paths, results) if isinstance(r, Exception)]
print(len(ok), "ok, peak concurrency:", peak)
print("failed:", failed)
print([r.get("city") or r.get("title") for r in ok][:6])12 ok, peak concurrency: 3
failed: [('/v1/courses/99', 'HTTPStatusError')]
['Dhaka', 'Chattogram', 'Sylhet', 'Khulna', 'Rajshahi', 'How AI Works']gatherreturns results in the order of the inputs, not in the order they finished, sozip(paths, results)is safe.- With
return_exceptions=True, one 404 becomes a value in the list instead of cancelling the whole batch. Without it, the first exception propagates and you lose the other results. - Python 3.11+ also has
asyncio.TaskGroup, which cancels the remaining tasks when one fails: the right choice when all results are needed or none. - For a rate limit (requests per minute) rather than a concurrency limit, add a token bucket; the page Caching, Rate Limiting and Reliability with Redis builds one.
Timeouts protect each request; a deadline protects the whole operation. A user-facing endpoint might allow 2 seconds for all its upstream calls together. asyncio.timeout() (Python 3.11+) cancels whatever is still running when time is up:
async def with_deadline():
async with httpx.AsyncClient(base_url=BASE_URL, timeout=10.0) as aclient:
try:
async with asyncio.timeout(1.0):
await asyncio.gather(fetch_slow(aclient, 0.2), fetch_slow(aclient, 3))
except TimeoutError:
print("deadline of 1 s exceeded: both requests were cancelled")
asyncio.run(with_deadline())deadline of 1 s exceeded: both requests were cancelledStreaming responses and SSE
An LLM generates its answer token by token, and users expect to see it appear the same way. Providers stream with Server-Sent Events: a response with Content-Type: text/event-stream whose body is lines like data: {...} separated by blank lines (Webhooks and Streaming with Server-Sent Events covers the format). With httpx, client.stream() gives you the response before the body has arrived, and aiter_lines() yields lines as they come:
import json
async def stream_chat(question):
async with httpx.AsyncClient(base_url=BASE_URL, timeout=httpx.Timeout(10.0, read=30.0)) as aclient:
login = await aclient.post("/v1/token", json={"username": "nadia", "password": "s3cret-pass"})
token = login.json()["access_token"]
payload = {"messages": [{"role": "user", "content": question}], "stream": True}
headers = {"Authorization": f"Bearer {token}"}
async with aclient.stream("POST", "/v1/chat", json=payload, headers=headers) as response:
response.raise_for_status()
print(response.headers["content-type"])
async for line in response.aiter_lines():
if not line.startswith("data: "):
continue # blank separators, comments, keep-alives
event = json.loads(line.removeprefix("data: "))
if event.get("done"):
print("\nusage:", event["usage"])
else:
print(event["delta"], end="", flush=True)
asyncio.run(stream_chat("What is an embedding?"))text/event-stream; charset=utf-8
This is a practice answer about: What is an embedding. A real model would say more.
usage: {'prompt_tokens': 4, 'completion_tokens': 16, 'total_tokens': 20}- The
async with ... stream(...)block matters: it guarantees the connection goes back to the pool even if you stop reading early (the user pressed "Stop"). - For streams, set a generous
readtimeout: it applies to the gap between chunks, so it is effectively "how long may the model go silent". - Real providers send richer events (
event:lines with types such ascontent_block_deltaorresponse.output_text.delta), but the loop is the same: read lines, parsedata:, switch on the type. The sync version iswith client.stream(...)anditer_lines().
Testing without the network: respx and MockTransport
Tests that call real APIs are slow, flaky, cost money (for LLMs, literally) and cannot easily produce the failures you most need to test: a 503, a timeout, a malformed payload. Mock the HTTP layer instead. respx intercepts httpx requests and answers them from routes you define; it ships a pytest fixture, respx_mock:
# file: test_bitbyte_client.py
import httpx
import pytest
from bitbyte_client import BitByteClient, NotFound, UpstreamError
BASE = "https://api.example.test"
COURSE = {"id": 8, "title": "RAG Systems", "level": "advanced", "hours": 10, "rating": 4.9}
@pytest.fixture
def bitbyte():
with BitByteClient(BASE) as client:
yield client
def test_get_course_returns_a_model(bitbyte, respx_mock):
route = respx_mock.get(f"{BASE}/v1/courses/8").respond(200, json=COURSE)
course = bitbyte.get_course(8)
assert course.title == "RAG Systems"
assert route.call_count == 1
def test_404_becomes_not_found(bitbyte, respx_mock):
respx_mock.get(f"{BASE}/v1/courses/99").respond(404, json={"detail": "Course 99 not found"})
with pytest.raises(NotFound, match="Course 99"):
bitbyte.get_course(99)
def test_timeout_becomes_upstream_error(bitbyte, respx_mock):
respx_mock.get(f"{BASE}/v1/weather").mock(side_effect=httpx.ReadTimeout("slow"))
with pytest.raises(UpstreamError, match="ReadTimeout"):
bitbyte.weather("Dhaka")
def test_changed_payload_is_caught(bitbyte, respx_mock):
broken = {**COURSE, "rating": "excellent"} # the upstream API changed a type
respx_mock.get(f"{BASE}/v1/courses/8").respond(200, json=broken)
with pytest.raises(UpstreamError, match="unexpected Course payload"):
bitbyte.get_course(8)
def test_query_parameters_are_sent(bitbyte, respx_mock):
route = respx_mock.get(f"{BASE}/v1/courses", params={"level": "advanced"}).respond(
200, json={"page": 1, "total": 1, "next_page": None, "items": [COURSE]}
)
assert [c.id for c in bitbyte.iter_courses(level="advanced")] == [8]
assert route.calls.last.request.url.params["per_page"] == "20"
def test_mock_transport_without_respx():
def handler(request: httpx.Request) -> httpx.Response:
assert request.headers["user-agent"] == "bitbyte-client/0.1"
return httpx.Response(200, json={"city": "Dhaka", "temp_c": 30, "humidity": 70, "condition": "Sunny"})
with BitByteClient(BASE, transport=httpx.MockTransport(handler)) as client:
assert client.weather("Dhaka").temp_c == 30.0uv run pytest -q...... [100%]
6 passed in 0.24sNotice that the tests use a fake base URL that does not exist: if a route were missing, respx would raise an error instead of letting a request escape to the internet. The last test uses httpx.MockTransport, which is built into httpx (and httpx2): a plain function receives each request and returns a response. That works with any library that lets you pass a transport, which is why the client accepts one.
Testing async code
respx works the same for AsyncClient. With pytest-asyncio, mark the test and make it async def. A side_effect list returns one response per call, which is how you test a retry loop:
# file: test_async_retry.py
import httpx
import pytest
async def get_with_one_retry(client: httpx.AsyncClient, url: str) -> httpx.Response:
response = await client.get(url)
if response.status_code == 503:
response = await client.get(url)
return response
@pytest.mark.asyncio
async def test_retries_once_after_503(respx_mock):
route = respx_mock.get("https://api.example.test/v1/flaky").mock(
side_effect=[httpx.Response(503), httpx.Response(200, json={"ok": True})]
)
async with httpx.AsyncClient() as client:
response = await get_with_one_retry(client, "https://api.example.test/v1/flaky")
assert response.json() == {"ok": True}
assert route.call_count == 2uv run pytest -q test_async_retry.py. [100%]
1 passed in 0.02sLogging without leaking secrets
When an LLM call fails at 3 a.m., logs are all you have, so you want method, path, status and timing for every request. You must not log API keys, bearer tokens, cookies or users' private prompts: logs are copied to log services, shared in tickets and kept for months. httpx's event hooks run your function on every request and response, so logging is written once:
SENSITIVE_HEADERS = {"authorization", "x-api-key", "cookie", "set-cookie", "proxy-authorization"}
def mask(value):
"""Keep just enough to tell two keys apart."""
return "***" + value[-4:] if len(value) > 8 else "***"
def safe_headers(headers):
return {k: (mask(v) if k.lower() in SENSITIVE_HEADERS else v) for k, v in headers.items()
if k.lower() in SENSITIVE_HEADERS | {"content-type", "x-request-id"}}
def log_request(request):
print("->", request.method, request.url.path, safe_headers(request.headers))
def log_response(response):
print("<-", response.status_code, response.request.method, response.request.url.path)
with httpx.Client(base_url=BASE_URL, event_hooks={"request": [log_request], "response": [log_response]}) as logged:
token = logged.post("/v1/token", json={"username": "nadia", "password": "s3cret-pass"}).json()["access_token"]
logged.get("/v1/me", headers={"Authorization": f"Bearer {token}", "X-Request-ID": "req-42"})
logged.post("/v1/reviews", headers={"X-API-Key": "practice-key-123"},
json={"course_id": 8, "rating": 5, "comment": "Clear and practical"})-> POST /v1/token {'content-type': 'application/json'}
<- 200 POST /v1/token
-> GET /v1/me {'authorization': '***-001', 'x-request-id': 'req-42'}
<- 200 GET /v1/me
-> POST /v1/reviews {'x-api-key': '***-123', 'content-type': 'application/json'}
<- 201 POST /v1/reviews- The password went in the JSON body, which the hook never prints. Log bodies only after deliberately removing personal data; for LLM apps, log token counts and a prompt id or hash, not the prompt.
- httpx itself logs
HTTP Request: GET https://... "HTTP/1.1 200 OK"atINFOlevel, including the full URL with its query string. That is one more reason never to put a key in a URL (?api_key=...): it ends up in your logs, the server's logs and every proxy in between. - For an
AsyncClient, the hooks must beasync deffunctions.
Packaging the client as a library
Once three services call the same API, copy-pasting bitbyte_client.py stops scaling. Make it a package with its own version. uv init --lib creates the standard src/ layout:
cd ~/projects
uv init -q --lib --vcs none bitbyte-client
cd bitbyte-client
cp ../api-clients/bitbyte_client.py src/bitbyte_client/client.py
uv add -q httpx pydantic
find . -path ./.venv -prune -o -type f -print | sort./.python-version
./README.md
./pyproject.toml
./src/bitbyte_client/__init__.py
./src/bitbyte_client/client.py
./src/bitbyte_client/py.typed
./uv.lockExpose the public names from the package's __init__.py, so users write from bitbyte_client import BitByteClient:
# file: src/bitbyte_client/__init__.py
"""Typed client for the BitByte Practice API."""
from bitbyte_client.client import (
BitByteClient,
BitByteError,
Course,
CoursePage,
NotFound,
UpstreamError,
Weather,
)
__all__ = ["BitByteClient", "BitByteError", "Course", "CoursePage", "NotFound", "UpstreamError", "Weather"]
__version__ = "0.1.0"uv build -q
ls dist
uv run python -c "import bitbyte_client; print(bitbyte_client.__version__, bitbyte_client.BitByteClient.__name__)"bitbyte_client-0.1.0-py3-none-any.whl
bitbyte_client-0.1.0.tar.gz
0.1.0 BitByteClientAnother project can now depend on it by path while you develop (uv add ../bitbyte-client, or pip install -e ../bitbyte-client), from a Git URL (uv add git+https://github.com/you/bitbyte-client), or from a private package index once it is published. A few rules make a client library pleasant to depend on:
- Let callers configure it: base URL, timeouts, and an optional transport or client. Never read global settings or call
httpx2.alias_httpx()inside a library. - Raise your own exceptions (one base class), and chain the original with
from excso the cause is still visible. - Log through
logging.getLogger(__name__)and never configure handlers: the application decides where logs go. - Ship types:
uv init --libalready added thepy.typedmarker, so editors and type checkers use your annotations. - Version it (semantic versioning) and keep a changelog: a renamed field is a breaking change for every service that uses it.
Where this shows up in AI work
- Embedding pipelines send thousands of chunks to an embedding API with an
AsyncClient, a semaphore set to the provider's concurrency limit, and retries on 429 that honourRetry-After. - Agents and tool calling run several tool calls in parallel with
gatheror aTaskGroup, under one deadline so the agent's turn cannot hang. - Chat backends stream provider tokens with
client.stream()and re-emit them to the browser (you build this in Building an LLM Backend with Streaming). - Provider SDKs (OpenAI, Anthropic) are exactly this design: a typed client over httpx2 with retries, timeouts and streaming built in. Knowing the layer underneath helps you set their
timeoutandmax_retriesoptions sensibly and debug them.
Common mistakes
- A new client per request.
httpx.get()in a loop, orasync with AsyncClient()inside an endpoint, pays a handshake every time and can exhaust sockets under load. Create one client at startup and share it. - Blocking calls inside
async def.requests.get()ortime.sleep()in a coroutine stalls every other task on the loop. UseAsyncClientandasyncio.sleep, or move blocking work to a thread withasyncio.to_thread(). - Retrying everything. Retrying a 400 just repeats the error; retrying a non-idempotent POST can do the action twice; retrying without backoff turns a provider's bad minute into an outage. Retry only transient failures, with jitter, a cap and a budget.
- Unbounded
gather.gather(*[call(x) for x in ten_thousand_items])opens as many requests as the pool allows and gets you rate-limited. Bound it with a semaphore and process in batches. - Secrets in URLs and logs. Query-string keys and logged headers leak. Send keys in headers, redact sensitive headers in hooks, and never log raw prompts or tokens.
Try it yourself
- Easy: with one
httpx.Client(base URL set), fetch the weather for all five cities and print the hottest one with its temperature. - Medium: write an async function
course_titles(ids, limit)that fetches the given course ids concurrently with at mostlimitrequests in flight and returns a dict{id: title}, skipping ids that return 404. Run it for ids 1 to 12 with a limit of 4. - Hard: write a pytest test (with respx) for
request_with_retriesfrom this page: the first two calls to/v1/flakyreturn 503 and the third returns 200, and the test asserts that the final status is 200 and that the route was called three times. Usebase_delay=0so the test is fast.
Answers
# 1. Easy
with httpx.Client(base_url=BASE_URL, timeout=5.0) as c:
reports = [c.get("/v1/weather", params={"city": city}).json() for city in cities]
hottest = max(reports, key=lambda r: r["temp_c"])
print(hottest["city"], hottest["temp_c"])
# 2. Medium
async def course_titles(ids, limit):
semaphore = asyncio.Semaphore(limit)
async def one(aclient, course_id):
async with semaphore:
response = await aclient.get(f"/v1/courses/{course_id}")
if response.status_code == 404:
return None
response.raise_for_status()
return response.json()
async with httpx.AsyncClient(base_url=BASE_URL, timeout=10.0) as aclient:
courses = await asyncio.gather(*(one(aclient, i) for i in ids))
return {c["id"]: c["title"] for c in courses if c is not None}
titles = asyncio.run(course_titles(range(1, 13), limit=4))
print(len(titles), titles[10])Rajshahi 33.6
10 LLMOpsFor the hard exercise, respx replaces the network and base_delay=0 removes the waiting. Go back to the first project, where retrying.py lives:
cd ~/projects/api-clients# file: test_retrying.py
import httpx
from retrying import request_with_retries
def test_flaky_endpoint_succeeds_on_third_attempt(respx_mock):
route = respx_mock.get("https://api.example.test/v1/flaky").mock(
side_effect=[httpx.Response(503), httpx.Response(503), httpx.Response(200, json={"ok": True})]
)
with httpx.Client(base_url="https://api.example.test") as client:
response = request_with_retries(client, "GET", "/v1/flaky", base_delay=0, log=lambda msg: None)
assert response.status_code == 200
assert route.call_count == 3uv run pytest -q test_retrying.py. [100%]
1 passed in 0.02sSummary
- httpx gives you the
requestsAPI plus async, streaming and HTTP/2, with a 5-second default timeout and no automatic redirects. httpx2 is its maintained fork with the same API (import httpx2 as httpx), already used by the OpenAI and Anthropic SDKs. - Share one
Client/AsyncClientper upstream service for connection pooling; setbase_url, headers, limits and explicit connect/read timeouts. - Retry only transient failures (connection errors, 429, 502–504), with exponential backoff, jitter,
Retry-Afterand a budget; never blindly retry a POST. - asyncio overlaps waiting:
gatherwith a semaphore bounds concurrency,return_exceptions=Trueor aTaskGroupdecides failure handling,asyncio.timeout()sets a deadline;client.stream()+aiter_lines()consumes SSE. - Wrap each API in a typed client that validates responses with Pydantic and raises its own exceptions; test it with respx or
MockTransport, log through hooks that redact secrets, and package it withuv init --libanduv build.
Next: FastAPI Architecture: Routers, Schemas and Error Handling switches sides: from calling APIs to structuring a FastAPI service of your own that is ready to grow.

