PythiloLesson 13 of 14 · progress kept in this browser

Share one async client across a batch

An AsyncClient can serve several requests within one async context. Reusing it expresses one client lifetime for the batch, instead of constructing a client for every item. With an ASGI transport the requests still run through the application's real routes without opening sockets.

Gather returns results in input order, even when tasks finish in a different order. Keep status checking inside the per-request coroutine so an invalid response does not become a misleading decoded value. The caller must await the batch from an event loop; asyncio.run is the entry point used by these standalone examples.

import asyncio, httpx
async def demo():
    transport = httpx.MockTransport(
        lambda r: httpx.Response(200,
            json={"path": r.url.path}))
    async with httpx.AsyncClient(
        transport=transport) as client:
        result = await client.get(
            "https://demo.test/one")
        print(result.json())
asyncio.run(demo())
Your task

Implement async read_squares(app,values) using one AsyncClient and ASGITransport. GET /square/{value} concurrently, raise for bad statuses, and return the square numbers in input order. An empty batch returns [].

The first run loads fastapi, httpx into this browser.