Python for AI Engineers · Part B · Lesson 11 of 26

Python httpx: HTTP requests, streaming and retries for LLM APIs

httpx for Java and JavaScript developers: GET and POST, JSON bodies, query params and auth, Client and AsyncClient with connection pooling, status codes, timeouts, retries that honour Retry-After, streaming an LLM reply line by line, and testing with MockTransport.

⏱ 40 min3 exercises that check your codeRuns in your browser

By the end you can

  • Send GET and POST requests with query params, JSON bodies, headers and auth, and read the JSON that comes back
  • Use one httpx.Client or httpx.AsyncClient per app so connections are pooled, and close it with with
  • Handle errors properly: raise_for_status, connect and read timeouts, and retries with backoff for 429 and 5xx that honour Retry-After
  • Read a streaming LLM reply (server-sent events) with iter_lines and aiter_lines
  • Test HTTP code with httpx.MockTransport, and call a model API by hand to see what the SDK does for you
1 / 6

1Why httpx

Every LLM app is an HTTP client: the model, the embeddings API, the vector database and most tools are reached over HTTP. In Python the classic library is requests. It is sync only, and it has no timeout by default: a call to a stuck server can wait forever.

httpx has almost the same API as requests, plus three things AI code needs: an async client next to the sync one, timeouts on by default (5 seconds), and optional HTTP/2. It is also what the official OpenAI and Anthropic Python SDKs use under the hood, so knowing it helps you read their errors.

Install it in a project from lesson 1 with the command below (we pin the version so the output matches this page), save the file as first.py, and run it. It makes a real request to PyPI, the Python package index, and asks it about httpx itself. After the lines uv add prints about installing packages, you should see the three lines below.

Run
uv add httpx==0.29.0
uv run python first.py
You should see
200 HTTP/1.1
application/json
httpx
first.py
import httpx

response = httpx.get("https://pypi.org/pypi/httpx/json")
print(response.status_code, response.http_version)
print(response.headers["content-type"])
print(response.json()["info"]["name"])
  1. httpx.get sends one GET and **waits** for the whole reply (it is synchronous). It returns an httpx.Response.line 3
  2. The status code is an int. http_version shows which protocol was used: HTTP/1.1 unless you turn on HTTP/2.line 4
  3. Headers work like a dict whose keys ignore case: "Content-Type" and "content-type" find the same header.line 5
  4. .json() parses the body into Python dicts and lists, like await res.json() in fetch.line 6
JavaScript (fetch)
const res = await fetch("https://pypi.org/pypi/httpx/json");
console.log(res.status);
console.log(res.headers.get("content-type"));
console.log((await res.json()).info.name);
// fetch has no timeout either: pass { signal: AbortSignal.timeout(5000) }
Java (java.net.http)
HttpClient client = HttpClient.newHttpClient();
HttpRequest req = HttpRequest.newBuilder(URI.create("https://pypi.org/pypi/httpx/json"))
    .timeout(Duration.ofSeconds(5))   // no timeout unless you set one
    .build();
HttpResponse<String> res = client.send(req, HttpResponse.BodyHandlers.ofString());
System.out.println(res.statusCode());
// parsing the JSON needs a library such as Jackson

For HTTP/2, install the extra with uv add "httpx[http2]==0.29.0" and create the client with httpx.Client(http2=True). response.http_version then says HTTP/2 when the server supports it (PyPI does). HTTP/2 sends many requests over one connection at the same time, which helps when you fire many calls at one API.

Tip A top-level httpx.get is fine for a one-off script. In an app, use a Client (section 4), which reuses connections.

2A fake server you can run here: MockTransport

The boxes on this page run Python in your browser, which cannot open normal network connections. That is not a problem, because httpx can send requests to a Python function instead of the network: httpx.MockTransport(handler). The handler receives each httpx.Request and returns an httpx.Response. Your client code does not change at all.

This is also exactly how you test HTTP code without a real server: no ports, no flaky network, no API bill. You will use it in the testing lesson and in every lab.

About the first two lines in these boxes: httpx is not built into the browser version of Python, so micropip downloads it the first time you press Run (a few seconds; that first run may also print a harmless APIVersionWarning from micropip above your output). The top-level await works here but not in a .py file. In your project you run uv add httpx==0.29.0 once and start the file at import httpx.

Try it: edit and run
import micropip                           # this page only: installs httpx into your browser
await micropip.install("httpx==0.29.0")   # in a project you run: uv add httpx==0.29.0

import httpx


def fake_server(request: httpx.Request) -> httpx.Response:
    """Plays the server: receives every request the client sends."""
    print("server got:", request.method, request.url)
    return httpx.Response(200, json={"model": "llama3.2:3b", "status": "ready"})


transport = httpx.MockTransport(fake_server)     # requests go to fake_server, not the network
with httpx.Client(transport=transport) as client:
    response = client.get("https://api.example.com/v1/health")

print(response.status_code, response.headers["content-type"])
print(response.text)            # the raw body, a str
print(response.json())          # the body parsed into a dict
print(response.json()["status"])
Expected output
server got: GET https://api.example.com/v1/health
200 application/json
{"model":"llama3.2:3b","status":"ready"}
{'model': 'llama3.2:3b', 'status': 'ready'}
ready

httpx.Response(200, json={...}) builds a response the same way a server would: it turns the dict into JSON text and sets the content-type header. response.text is that raw text (httpx writes JSON compactly, without spaces); response.json() turns it back into a dict. with httpx.Client(...) as client: creates a client and closes it at the end of the block, like Java's try-with-resources.

Tip Keep the fake server as dumb as possible: return a fixed response, or pick one from the request URL. Then your test checks your code, not the fake.

3Query params, JSON bodies, headers and auth

You never build URLs or bodies by hand. params= takes a dict and adds an encoded query string. json= takes a dict, turns it into JSON and sets Content-Type: application/json. headers= adds headers. Model APIs authenticate with a header Authorization: Bearer <key>; for HTTP Basic auth pass auth=(user, password).

The fake server below prints what actually goes over the wire, so you can see each option at work. request.content is the raw body as bytes; .decode() turns it into a str (it is empty for a GET).

Try it: edit and run
import micropip                           # this page only: installs httpx into your browser
await micropip.install("httpx==0.29.0")   # in a project you run: uv add httpx==0.29.0

import httpx


def fake_server(request):
    print(request.method, request.url)
    print("  authorization:", request.headers.get("authorization"))
    print("  content-type: ", request.headers.get("content-type"))
    if request.content:
        print("  body:", request.content.decode())
    return httpx.Response(200, json={"ok": True})


API_KEY = "sk-test-123"        # a fake key: real keys come from .env (lesson 10)
auth_header = {"Authorization": f"Bearer {API_KEY}"}

with httpx.Client(transport=httpx.MockTransport(fake_server)) as client:
    client.get(
        "https://api.example.com/v1/search",
        params={"q": "vector db", "limit": 5},
        headers=auth_header,
    )
    client.post(
        "https://api.example.com/v1/chat/completions",
        json={"model": "llama3.2:3b", "messages": [{"role": "user", "content": "Hi"}]},
        headers=auth_header,
    )
    client.get("https://api.example.com/v1/admin", auth=("admin", "s3cret"))
Expected output
GET https://api.example.com/v1/search?q=vector+db&limit=5
  authorization: Bearer sk-test-123
  content-type:  None
POST https://api.example.com/v1/chat/completions
  authorization: Bearer sk-test-123
  content-type:  application/json
  body: {"model":"llama3.2:3b","messages":[{"role":"user","content":"Hi"}]}
GET https://api.example.com/v1/admin
  authorization: Basic YWRtaW46czNjcmV0
  content-type:  None
JavaScript (fetch)
const url = new URL("https://api.example.com/v1/chat/completions");
const res = await fetch(url, {
  method: "POST",
  headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
  body: JSON.stringify({ model: "llama3.2:3b", messages: [{ role: "user", content: "Hi" }] }),
});
Java (java.net.http)
String body = mapper.writeValueAsString(payload); // Jackson
HttpRequest req = HttpRequest.newBuilder(URI.create(baseUrl + "/chat/completions"))
    .header("Authorization", "Bearer " + apiKey)
    .header("Content-Type", "application/json")
    .POST(HttpRequest.BodyPublishers.ofString(body))
    .build();

Look at what httpx did for you: the space in "vector db" became + and the number 5 became text in the URL; the json= dict became compact JSON with the right content type; auth=("admin", "s3cret") became a Basic header holding the base64 of admin:s3cret. headers.get(...) returns None when a header is missing, like dict.get.

Watch out Use json= for JSON APIs, not data=. data= sends a form (application/x-www-form-urlencoded), and a model API answers it with a 400 or 422 error that does not say why.

4Client and AsyncClient: one client, pooled connections

Opening a connection costs a TCP handshake and, for HTTPS, a TLS handshake: often 50 to 200 ms before the first byte of your request. httpx.get(...) pays it on every call. An httpx.Client keeps a pool of open connections and reuses them (keep-alive), like sharing one Java HttpClient or one Node keep-alive agent. By default it keeps up to 100 connections, 20 of them idle.

A client also holds settings for every request it sends: base_url, default headers and timeout. Create one per app (or per API), reuse it everywhere, and close it once at the end; with (or async with) does the closing.

httpx.AsyncClient is the async twin with the same methods, which you await. Use it inside async code (FastAPI endpoints, agents) together with asyncio.gather from lesson 9 to make several calls at once. Here the fake server is itself an async def that waits a different time for each prompt, like a model taking longer on some.

Like in lesson 9, the box ends with await main() because the browser already runs an event loop. In a .py file you write asyncio.run(main()) instead, usually under if __name__ == "__main__":, a check that is true only when you run that file directly (not when another file imports it), like Java's public static void main.

Try it: edit and run
import micropip                           # this page only: installs httpx into your browser
await micropip.install("httpx==0.29.0")   # in a project you run: uv add httpx==0.29.0

import asyncio
import json

import httpx

DELAYS = {"summarize": 0.3, "translate": 0.1, "classify": 0.2}


async def fake_server(request):
    prompt = json.loads(request.content)["prompt"]
    await asyncio.sleep(DELAYS[prompt])          # the "model" takes a while
    print("  server finished", prompt)
    return httpx.Response(200, json={"answer": prompt.upper()})


async def ask(client, prompt):
    response = await client.post("/generate", json={"prompt": prompt})
    return response.json()["answer"]


async def main():
    async with httpx.AsyncClient(
        base_url="https://api.example.com/v1",
        headers={"Authorization": "Bearer sk-test-123"},
        transport=httpx.MockTransport(fake_server),
    ) as client:
        request = client.build_request("POST", "/generate")
        print("full URL:", request.url)
        answers = await asyncio.gather(*(ask(client, p) for p in DELAYS))
        print(answers)


await main()   # in a .py file: asyncio.run(main())
Expected output
full URL: https://api.example.com/v1/generate
  server finished translate
  server finished classify
  server finished summarize
['SUMMARIZE', 'TRANSLATE', 'CLASSIFY']

base_url is joined with each path: "/generate" becomes https://api.example.com/v1/generate, keeping the /v1 (build_request builds a request without sending it, handy to check a URL). All three posts share one client, so in real life they share its connection pool. The server finishes them in order of speed, yet gather returns the answers in the order you asked, as in lesson 9.

Watch out Creating a new Client inside a function that runs for every request (with httpx.Client() as c: in each call) throws the pool away each time: you pay the handshakes again and can run out of sockets under load. Create the client once at startup and pass it in.

5Status codes and raise_for_status

Like fetch and Java's HttpClient, httpx does not raise an exception for a 404 or a 500. You get a normal response and must check it. response.is_success is true for 2xx; response.raise_for_status() raises httpx.HTTPStatusError for 4xx and 5xx and does nothing otherwise. The error carries the response, so you can read the API's error message from it.

For an LLM API the codes you will meet most: 400 bad request (wrong JSON shape), 401 wrong or missing key, 404 unknown model, 429 rate limited, 500/502/503 the provider has a problem. Only 429 and 5xx are worth retrying.

Try it: edit and run
import micropip                           # this page only: installs httpx into your browser
await micropip.install("httpx==0.29.0")   # in a project you run: uv add httpx==0.29.0

import httpx


def fake_server(request):
    status = int(request.url.params["status"])   # the test asks for a status code
    return httpx.Response(status, json={"error": {"message": f"fake error {status}"}})


with httpx.Client(transport=httpx.MockTransport(fake_server), base_url="https://api.example.com") as client:
    r = client.get("/v1/test", params={"status": 404})
    print(r.status_code, r.reason_phrase, "| success:", r.is_success)   # no exception yet

    for status in [200, 401, 429, 503]:
        r = client.get("/v1/test", params={"status": status})
        try:
            r.raise_for_status()
            print(status, "ok")
        except httpx.HTTPStatusError as e:
            print(status, "raised:", e.response.json()["error"]["message"])
Expected output
404 Not Found | success: False
200 ok
401 raised: fake error 401
429 raised: fake error 429
503 raised: fake error 503

request.url.params reads the query string back as a dict-like object, which lets one fake server play many scenarios. reason_phrase is the standard text for the code. raise_for_status() also returns the response when it does not raise, so you can chain: data = client.get(url).raise_for_status().json().

All httpx errors share one base class, so you can catch as broadly or as narrowly as you need:

httpx.HTTPError
├── httpx.HTTPStatusError      raise_for_status() saw 4xx or 5xx
└── httpx.RequestError         the request did not get a response
    └── httpx.TransportError
        ├── httpx.TimeoutException
        │   ├── httpx.ConnectTimeout
        │   ├── httpx.ReadTimeout
        │   ├── httpx.WriteTimeout
        │   └── httpx.PoolTimeout
        └── httpx.NetworkError
            └── httpx.ConnectError   e.g. Connection refused: the server is not running

6Timeouts: connect, read, write and pool

An httpx timeout is not one number for the whole call. There are four, all 5 seconds by default: connect (to open the connection), read (the longest wait for the next piece of the reply), write (to send a piece of the request) and pool (to wait for a free connection from the pool). httpx.Timeout(60.0, connect=5.0) means 60 seconds for each, except 5 for connect.

This matters a lot for models. A non-streaming chat call sends nothing back until the whole answer is generated, which can take 20 seconds or more, so the default 5 second read timeout fails long answers. Give model calls a long read timeout and a short connect timeout: if the server is down you want to know in seconds. The OpenAI SDK does exactly that: 600 seconds overall, 5 for connect.

Below the fake server raises httpx.ReadTimeout, the same error httpx raises when no byte arrives in time, so you can see how your code handles it without waiting.

Try it: edit and run
import micropip                           # this page only: installs httpx into your browser
await micropip.install("httpx==0.29.0")   # in a project you run: uv add httpx==0.29.0

import httpx

print(httpx.Timeout(5.0))                   # the default for every client
model_timeout = httpx.Timeout(60.0, connect=5.0)
print(model_timeout)


def stuck_server(request):
    raise httpx.ReadTimeout("no reply in time", request=request)


with httpx.Client(transport=httpx.MockTransport(stuck_server), timeout=model_timeout) as client:
    try:
        client.post("https://api.example.com/v1/chat/completions", json={"model": "llama3.2:3b"})
    except httpx.TimeoutException as e:      # catches all four kinds of timeout
        print(type(e).__name__, "->", e)
    print("client timeout:", client.timeout)
Expected output
Timeout(timeout=5.0)
Timeout(connect=5.0, read=60.0, write=60.0, pool=60.0)
ReadTimeout -> no reply in time
client timeout: Timeout(connect=5.0, read=60.0, write=60.0, pool=60.0)

timeout= on the client sets the default for every request; a single call can override it with client.post(..., timeout=120.0). type(e).__name__ is the class name of the error, the way you would call e.getClass().getSimpleName() in Java. timeout=None turns timeouts off completely: almost never what you want.

Watch out The read timeout is the gap between bytes, not a deadline for the whole call. A stream that sends a token every second never times out even if it runs for ten minutes. For a deadline on the whole call, wrap it in asyncio.timeout(...) from lesson 9.

7Retries with backoff for 429 and 5xx

Some failures go away if you wait: a timeout, a connection error, a 429 (rate limit), a 5xx (the provider is overloaded). Retry those a few times with exponential backoff (wait 0.5 s, then 1, then 2) plus jitter (a random part, so a thousand clients do not all retry at the same instant). Never retry a 400 or a 401: the same request fails the same way again.

When a server sends a Retry-After header with a 429 or 503, it tells you how many seconds to wait. Honour it instead of guessing. (It can also be an HTTP date; this example handles the common number form and falls back to backoff otherwise.)

The function below takes the client and the request options, and a sleep function as a parameter. Real code leaves the default time.sleep; the demo passes a function that only prints, so it runs instantly. Passing a dependency in like this is also how you test retry code. The jitter comes from random.Random(7), a random generator with a fixed seed, so this page prints the same numbers every run.

Try it: edit and run
import micropip                           # this page only: installs httpx into your browser
await micropip.install("httpx==0.29.0")   # in a project you run: uv add httpx==0.29.0

import random
import time

import httpx

RETRY_STATUSES = {429, 500, 502, 503, 504}
rng = random.Random(7)          # fixed seed for the demo; real code can use the random module directly


def backoff(attempt, base=0.5, cap=8.0):
    """0.5, 1, 2, 4 ... seconds, at most cap, with up to 10% random jitter added."""
    wait = min(cap, base * 2 ** (attempt - 1))
    return wait + rng.uniform(0, wait * 0.1)


def retry_after(response):
    value = response.headers.get("retry-after", "")
    return float(value) if value.isdigit() else None    # "2" -> 2.0; a date or nothing -> None


def send_with_retry(client, method, url, attempts=4, sleep=time.sleep, **kwargs):
    for attempt in range(1, attempts + 1):
        try:
            response = client.request(method, url, **kwargs)
        except (httpx.TimeoutException, httpx.ConnectError) as e:
            if attempt == attempts:
                raise                                   # out of attempts: let the caller see it
            reason, wait = type(e).__name__, backoff(attempt)
        else:
            if response.status_code not in RETRY_STATUSES or attempt == attempts:
                return response                         # success, a non-retryable error, or the last try
            reason = response.status_code
            wait = retry_after(response) or backoff(attempt)
        print(f"attempt {attempt}: {reason}, retrying in {wait:.2f} s")
        sleep(wait)


replies = iter([
    "timeout",
    httpx.Response(503),
    httpx.Response(429, headers={"Retry-After": "2"}),
    httpx.Response(200, json={"answer": "42"}),
])


def flaky_server(request):
    reply = next(replies)
    if reply == "timeout":
        raise httpx.ReadTimeout("slow", request=request)
    return reply


with httpx.Client(transport=httpx.MockTransport(flaky_server)) as client:
    r = send_with_retry(client, "POST", "https://api.example.com/v1/chat", json={"q": "?"},
                        sleep=lambda s: None)          # demo: do not really wait
    print(r.status_code, r.json())
Expected output
attempt 1: ReadTimeout, retrying in 0.52 s
attempt 2: 503, retrying in 1.02 s
attempt 3: 429, retrying in 2.00 s
200 {'answer': '42'}

Read send_with_retry from the top. client.request(method, url, **kwargs) is the general form of client.get and client.post, and **kwargs forwards json=, params= and the rest (lesson 4). try / except / else: the else part runs only when no exception was raised, so it handles responses while except handles network trouble. The 429 waited exactly the 2 seconds the server asked for. The fake server pops its next scripted reply from an iterator (lesson 8) on each call.

httpx also has httpx.HTTPTransport(retries=3), but that only retries failed connections (ConnectError, ConnectTimeout), never a 429 or a 503. The OpenAI SDK retries 408, 409, 429 and 5xx twice by default (max_retries=2) and honours Retry-After: one more reason to use the SDK for model calls and keep a helper like this for your own services and tools.

Watch out Retrying a POST that changes something (charges a card, sends an email) can do it twice if the first attempt reached the server but the reply was lost. Retry only safe requests, or send an idempotency key the server uses to drop duplicates. A chat completion is safe to retry; it just costs tokens again.

8Streaming: what an LLM stream looks like on the wire

With "stream": true, a model API does not send one JSON reply. It keeps the response open and sends server-sent events (SSE, content type text/event-stream): lines of text that start with data: , each holding a small JSON chunk with the next piece of the answer, separated by blank lines. OpenAI-compatible APIs (OpenAI, Ollama, vLLM) end with data: [DONE].

To read it as it arrives, use client.stream(...) in a with block instead of client.post(...): the body is not downloaded up front, and response.iter_lines() hands you one line at a time as bytes come in. The network splits the body into chunks anywhere, even in the middle of a line; iter_lines puts the lines back together for you. The fake server below sends its body in four chunks, one of them cut mid-line, to show that.

Try it: edit and run
import micropip                           # this page only: installs httpx into your browser
await micropip.install("httpx==0.29.0")   # in a project you run: uv add httpx==0.29.0

import json

import httpx

WIRE = [                                         # the body exactly as the bytes arrive
    b'data: {"choices":[{"delta":{"content":"Par"}}]}\n\n',
    b'data: {"choices":[{"delta":{"content":"is is"}}]}\n\ndata: {"choi',   # cut mid-line
    b'ces":[{"delta":{"content":" the capital."}}]}\n\n',
    b"data: [DONE]\n\n",
]


def fake_model(request):
    return httpx.Response(200, headers={"content-type": "text/event-stream"}, content=iter(WIRE))


body = {"model": "llama3.2:3b", "stream": True, "messages": [{"role": "user", "content": "Capital of France?"}]}

with httpx.Client(transport=httpx.MockTransport(fake_model), base_url="https://api.example.com/v1") as client:
    with client.stream("POST", "/chat/completions", json=body) as response:
        response.raise_for_status()
        for line in response.iter_lines():
            print(repr(line))                    # repr shows the exact text, quotes and all

    print("--- as a user sees it:")
    with client.stream("POST", "/chat/completions", json=body) as response:
        for line in response.iter_lines():
            if not line.startswith("data: "):
                continue                         # blank lines only separate events
            data = line.removeprefix("data: ")
            if data == "[DONE]":
                break
            piece = json.loads(data)["choices"][0]["delta"].get("content", "")
            print(piece, end="", flush=True)
        print()
Expected output
'data: {"choices":[{"delta":{"content":"Par"}}]}'
''
'data: {"choices":[{"delta":{"content":"is is"}}]}'
''
'data: {"choices":[{"delta":{"content":" the capital."}}]}'
''
'data: [DONE]'
''
--- as a user sees it:
Paris is the capital.

The first loop shows the raw lines: every event line is followed by an empty line, and the chunk that was cut in two came out as one whole line. In the second loop, removeprefix (Python 3.9+) drops the data: part, json.loads parses the rest, and .get("content", "") copes with chunks that carry no text. print(..., end="", flush=True) writes each piece straight away without a newline, so the answer appears as it is generated.

The async version is the same with async with and async for, and aiter_lines() instead of iter_lines():

async with client.stream("POST", "/chat/completions", json=body) as response:
    async for line in response.aiter_lines():
        ...   # same parsing as above

Inside with client.stream(...) the connection stays checked out of the pool until the block ends, so always use the with form. You will serve this kind of stream to a browser yourself in the streaming chat lab.

9Calling a model API by hand, and what the SDK adds

Now put it together against a real model. This file calls Ollama's OpenAI-compatible API (from lab 1) with plain httpx: once for a whole answer, once streamed. It cannot run in the browser, because it needs a model server on your machine. Start Ollama, make sure llama3.2:3b is pulled, save the file as chat_by_hand.py in your project and run it.

Run
ollama pull llama3.2:3b
uv run python chat_by_hand.py
You should see
tokens used: 41
DNS translates human-readable domain names into the IP addresses computers use to find each other.
GET, POST and DELETE.
chat_by_hand.py
import json

import httpx

BASE_URL = "http://localhost:11434/v1"     # Ollama's OpenAI-compatible API
API_KEY = "ollama"                         # Ollama ignores it; hosted APIs need a real key
MODEL = "llama3.2:3b"


def ask(client: httpx.Client, question: str) -> str:
    response = client.post("/chat/completions", json={
        "model": MODEL,
        "messages": [{"role": "user", "content": question}],
    })
    response.raise_for_status()
    data = response.json()
    print("tokens used:", data["usage"]["total_tokens"])
    return data["choices"][0]["message"]["content"]


def stream(client: httpx.Client, question: str) -> None:
    body = {"model": MODEL, "stream": True, "messages": [{"role": "user", "content": question}]}
    with client.stream("POST", "/chat/completions", json=body) as response:
        response.raise_for_status()
        for line in response.iter_lines():
            if not line.startswith("data: ") or line == "data: [DONE]":
                continue
            chunk = json.loads(line.removeprefix("data: "))
            if chunk["choices"]:
                print(chunk["choices"][0]["delta"].get("content") or "", end="", flush=True)
    print()


def main() -> None:
    timeout = httpx.Timeout(120.0, connect=5.0)
    headers = {"Authorization": f"Bearer {API_KEY}"}
    with httpx.Client(base_url=BASE_URL, headers=headers, timeout=timeout) as client:
        print(ask(client, "What is DNS? One sentence."))
        stream(client, "Name three HTTP methods. Answer in five words or fewer.")


if __name__ == "__main__":
    main()
  1. The /v1 path is the OpenAI-compatible API. Point BASE_URL at another provider and the same code works there.line 5
  2. POST /chat/completions with the model and the messages: this is the request every OpenAI-compatible SDK sends for you.line 11
  3. A 404 here usually means the model is not pulled; a ConnectError means Ollama is not running.line 15
  4. usage tells you how many tokens the call used, which is what a hosted API bills you for.line 17
  5. The answer is inside the first (usually only) choice.line 18
  6. Some servers send a last chunk with an empty choices list (for example carrying usage), so check before indexing.line 29
  7. .get("content") or "" turns both a missing and a null content into an empty string.line 30
  8. 120 s to read (a local model can be slow to start), 5 s to connect (fail fast if Ollama is down).line 35
  9. One client for both calls: base URL, auth header and timeouts are set once.line 37
  10. True only when you run this file directly, not when another file imports it. Same idea as public static void main in Java.line 42
Python, the openai SDK
from openai import OpenAI

client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
r = client.chat.completions.create(
    model="llama3.2:3b",
    messages=[{"role": "user", "content": "What is DNS? One sentence."}],
)
print(r.usage.total_tokens)
print(r.choices[0].message.content)
Java (java.net.http)
var client = HttpClient.newBuilder()
    .connectTimeout(Duration.ofSeconds(5)).build();
var req = HttpRequest.newBuilder(URI.create("http://localhost:11434/v1/chat/completions"))
    .header("Authorization", "Bearer ollama")
    .header("Content-Type", "application/json")
    .timeout(Duration.ofSeconds(120))
    .POST(HttpRequest.BodyPublishers.ofString(json)) // json built with Jackson
    .build();
var res = client.send(req, HttpResponse.BodyHandlers.ofString());

The model writes its own words, so your answers and the token count will differ from the box above; the shape is what matters. The SDK sends the very same request: compare the two Python versions. On top it gives you typed objects instead of dicts, retries for 429 and 5xx, sensible timeouts, a typed error per status code, and stream parsing. Use the SDK for model calls in real apps. Writing it by hand once means you can debug it: when the SDK says APIStatusError 404, you know exactly which request and which reply it means.

Tip httpx logs every request at INFO level on the logger named httpx. Add import logging; logging.basicConfig(level=logging.INFO) at the top and you see each call, for example HTTP Request: POST http://localhost:11434/v1/chat/completions "HTTP/1.1 200 OK". It works for the OpenAI SDK too, since it uses httpx.

Common mistakes

  • Using requests, or a sync httpx.Client, inside async def code: it blocks the event loop. Use httpx.AsyncClient there.
  • Creating a new client for every request, which throws away the connection pool. Create one client at startup and reuse it.
  • Assuming a 4xx or 5xx raises an exception. It does not: call response.raise_for_status() or check response.status_code.
  • Keeping the default 5 second read timeout for a non-streaming model call, so long answers fail with ReadTimeout. Use something like httpx.Timeout(120.0, connect=5.0).
  • Retrying every error, including 400 and 401, or ignoring Retry-After on a 429. Retry only timeouts, connection errors, 429 and 5xx, with backoff.
  • Calling client.post with "stream": true and reading response.text: it waits for the whole answer. Use client.stream(...) and iter_lines().

Practice

Write the code, then press Check. Your work is saved in this browser.

1How long to wait?

Write should_retry(status), which is True for 429 and every 5xx (500 to 599) and False otherwise, and wait_seconds(headers, attempt, base=0.5, cap=8.0). headers is a dict with lowercase keys. If it has a "retry-after" value made only of digits, return that number as a float. Otherwise return the backoff base * 2 ** (attempt - 1), but never more than cap. No jitter, so the result is easy to test.

Exercise
def should_retry(status):
    return status >= 400                 # too broad: 400 and 401 never succeed on a retry


def wait_seconds(headers, attempt, base=0.5, cap=8.0):
    return base                          # ignores Retry-After and never grows


print(should_retry(429), should_retry(404))
print(wait_seconds({"retry-after": "3"}, 1), wait_seconds({}, 3))
Hint

`return status == 429 or 500 <= status <= 599`. For the wait: `value = headers.get("retry-after", "")`, then `if value.isdigit(): return float(value)`, else `return min(cap, base * 2 ** (attempt - 1))`.

2Parse an SSE stream

Write parse_sse(lines). lines is an iterable of str lines, exactly what response.iter_lines() yields for an OpenAI-compatible stream. Return the full answer text: the content of each chunk's first choice delta, joined together. Skip blank lines and comment lines that start with : (servers send : keep-alive), skip chunks whose choices list is empty or whose delta has no content (or null), and stop at data: [DONE].

Exercise
import json


def parse_sse(lines):
    text = ""
    for line in lines:
        chunk = json.loads(line[6:])     # crashes on blank lines and on [DONE]
        text += chunk["choices"][0]["delta"]["content"]
    return text


print(parse_sse(['data: {"choices":[{"delta":{"content":"Hi"}}]}']))
Hint

In the loop: `if not line.startswith("data: "): continue`, then `data = line.removeprefix("data: ")`, `if data == "[DONE]": break`. Parse with `json.loads`, check `chunk["choices"]`, and add `delta.get("content") or ""`.

3Put the lines back together

The network cuts a streamed body into chunks anywhere, even mid-line. Write a generator split_lines(chunks) (it uses yield, lesson 8) that takes an iterable of str chunks and yields complete lines without the "\n", the way iter_lines does. Keep the unfinished end of a chunk until the next chunk completes it. If text is left over after the last chunk, yield it too.

Exercise
def split_lines(chunks):
    for chunk in chunks:
        yield from chunk.split("\n")     # wrong: a line cut in two comes out as two pieces


print(list(split_lines(["data: he", "llo\n\ndata: [DO", "NE]\n"])))
Hint

Keep a `buffer = ""`. For each chunk: `buffer += chunk`, then `while "\n" in buffer:` use `line, buffer = buffer.split("\n", 1)` and `yield line`. After the loop, `if buffer: yield buffer`.

Interview questions

Q1Why would you choose httpx over requests for an AI service?

httpx has the same simple API plus an async client (AsyncClient) for use inside asyncio and FastAPI, timeouts on by default (requests has none, so a stuck call can hang forever), optional HTTP/2, and MockTransport for testing. It is also what the OpenAI and Anthropic Python SDKs are built on.

Q2What is connection pooling and how do you get it in httpx?

Keeping TCP/TLS connections open and reusing them for later requests to the same host, which skips the handshakes (often tens to hundreds of milliseconds each). In httpx you get it by creating one httpx.Client or httpx.AsyncClient and reusing it for the app's lifetime; module-level httpx.get opens and closes a connection every time.

Q3Explain httpx's connect and read timeouts. What would you set for an LLM call?

Connect is how long to wait to open a connection; read is the longest gap allowed between received bytes, not a total deadline (there are also write and pool timeouts). All default to 5 s. For a model call use a short connect timeout (about 5 s, fail fast if the server is down) and a long read timeout (60 to 600 s), because a non-streaming reply sends nothing until generation finishes. For a total deadline wrap the call in asyncio.timeout.

Q4How would you implement retries for a model API?

Retry only transient failures: timeouts, connection errors, 429 and 5xx; never 400 or 401. Use a small number of attempts with exponential backoff and jitter, honour Retry-After when the server sends it, and make writes idempotent (or use an idempotency key). With the OpenAI SDK this is built in via max_retries.

Q5How does LLM streaming work at the HTTP level?

The server keeps one response open with content type text/event-stream and writes server-sent events: data: {json chunk} lines separated by blank lines, ending with data: [DONE] for OpenAI-compatible APIs. The client reads it incrementally (client.stream + iter_lines or aiter_lines), parses each data: line and appends choices[0].delta.content.

Q6How do you unit test code that calls an HTTP API without a real server?

Inject the client and give it transport=httpx.MockTransport(handler), where the handler is a function that receives the httpx.Request and returns an httpx.Response. The test can assert on the request (URL, headers, JSON body) and script responses such as 429 then 200 to test retries, with no network, ports or cost.