APIs for AIFastAPI 0.141 · httpx2 2.13 · Python 3.10+
0%
1
Curious builder0 XP earned · 300 to level 2
0 daysFinish a lesson to begin
Badge collection0 of 6 unlocked
19 small wins to finish your pathNext lesson

MockTransport: a server you write as a function

A client sends requests and hands you the responses. Before calling a real server, give the client a function to call instead, so you can see exactly what it sends.

Example
import httpx2

def fake_server(request):
    print("server got:", request.method, request.url.path)
    return httpx2.Response(200, json={"id": 2, "customer": "Ben"})

client = httpx2.Client(transport=httpx2.MockTransport(fake_server), base_url="https://api.example.com")

response = client.get("/tickets/2")
print(response.status_code, response.json())

httpx2.Client is the object that sends requests. A transport is the part that actually delivers them; normally that is the network. MockTransport delivers each request to your function and returns whatever response the function makes.

base_url is put in front of every path, so client.get("/tickets/2") asks for https://api.example.com/tickets/2. Nothing left your computer.

A fake server that decides

Example
TICKETS = {1: "I was charged twice for one order", 2: "My parcel has not arrived"}

def fake_server(request):
    ticket_id = int(request.url.path.split("/")[-1])
    if ticket_id not in TICKETS:
        return httpx2.Response(404, json={"detail": "ticket not found"})
    return httpx2.Response(200, json={"id": ticket_id, "text": TICKETS[ticket_id]})

client = httpx2.Client(transport=httpx2.MockTransport(fake_server), base_url="https://api.example.com")
for ticket_id in (1, 9):
    response = client.get(f"/tickets/{ticket_id}")
    print(response.status_code, response.json())

request.url.path.split("/") cuts /tickets/9 at each slash, and [-1] takes the last piece, the id. The same client code gets a 200 for one ticket and a 404 for the other.

Why this matters: code that calls a paid model API is code you want to test without paying. A mock transport lets a test decide exactly what the API answers, including the errors that are hard to cause on purpose. Lesson 12 uses it for exactly that.

Try it yourself
  • Make fake_server return 500 for ticket 1 and run the loop.
  • Print request.headers inside fake_server, then pass headers={"X-Team": "support"} to client.get.
  • Call client.post("/tickets", json={"text": "hi"}) and print request.content in the server.

Slow is fine. Stopping is the only problem.