- Open one shared
ClientSessionat FastAPI startup and close it at shutdown, in a FastAPIlifespan - Hand the session to endpoints through the lifespan state and
Depends - Turn upstream failures (connection errors, timeouts, non-2xx answers) into a
502 - Run several upstream calls concurrently with
asyncio.gather - Use the session deep in a codebase without passing it through every function (
/endpoint_complex_codebase)
fastAPI.py: the app, itslifespanand the endpointshttp_client.py: theHTTPClientdependency and thefetch_jsonhelperservices.py: service classes used by/endpoint_complex_codebase
/endpoint and /endpoint_multi receive the session with Depends and pass it as an argument.
That's fine for one level, but in a real codebase the HTTP call is often several functions deep.
/endpoint_complex_codebase shows how to avoid passing the session through every call:
each class receives what it needs once, in its constructor, and FastAPI builds the chain for every request.
endpoint_complex_codebase(report: Report) # only asks for the service
-> ReportService(upstream: UpstreamAPI) # business logic, never sees the session
-> UpstreamAPI(client: HTTPClient) # the only class that talks HTTP
-> aiohttp.ClientSession # opened and closed by the lifespan
Inside the classes, methods use self.upstream / self.client, so no call takes the session as an argument.
| Where the session lives | You write | Cost |
|---|---|---|
| Function arguments | f(client, ...) at every level |
Verbose once the calls get deep |
| An object (this repo's services) | One Depends per endpoint, self.client inside |
Needs a class |
| A module global set by the lifespan | get_client() anywhere |
Hidden dependency; tests must patch the global |
uv sync --all-extras
uv run python src/fastAPI_aiohttp/fastAPI.pyuv run pytestThe tests start a fake upstream server with aiohttp's own
TestServer, and point the app's session at it
with app.dependency_overrides (the session uses a base_url, so only the host changes).
One override reaches the session everywhere, including deep inside UpstreamAPI.
aioresponses is not used: it is broken with aiohttp 3.14 (#289).