FastAPI Lifespan Dependency State

Manage shared resources with FastAPI lifespan context, wiring async clients into dependency injection with clean startup and shutdown.

PythonFastapiConfig Management

Code

pythonsnippet
43 lines
import asyncio
from contextlib import asynccontextmanager

import httpx
from fastapi import Depends, FastAPI


@asynccontextmanager
async def lifespan(app: FastAPI):
    app.state.http = httpx.AsyncClient(
        timeout=httpx.Timeout(10.0),
        limits=httpx.Limits(max_connections=50),
    )
    app.state.queue = asyncio.Queue(maxsize=1000)
    print('resources ready')
    yield
    await app.state.http.aclose()
    print('resources released')


app = FastAPI(lifespan=lifespan)


async def get_client(request) -> httpx.AsyncClient:
    return request.app.state.http


async def get_queue(request) -> asyncio.Queue:
    return request.app.state.queue


@app.get('/prices/{symbol}')
async def price(symbol: str, client: httpx.AsyncClient = Depends(get_client)):
    resp = await client.get(f'https://api.example.com/p/{symbol}')
    return {'symbol': symbol, 'data': resp.json()}


@app.post('/alerts')
async def enqueue(payload: dict, queue: asyncio.Queue = Depends(get_queue)):
    if queue.full():
        return {'queued': False, 'reason': 'backpressure'}
    await queue.put(payload)
    return {'queued': True, 'depth': queue.qsize()}

Inside the snippet

Structurally, expect the functions lifespan, get_client, get_queue and price and nothing else.

Await points sequence the coroutines; a failure lands where the result is consumed. asynccontextmanager, Depends, FastAPI are the only symbols borrowed from fastapi — the coupling is explicit and narrow.

The result is a fresh construction, so callers can keep their originals.

Caveats

  • Dependency check: fastapi, asyncio and httpx — not built-in, must be present in the project.

Putting it to use

The main signature reads def lifespan(app: FastAPI)

Running the file prints labeled results such as resources ready, resources released — each operation’s effect is visible in the output.

lifespan is what another module would consume; nothing else here is load-bearing for callers.

Core lines

resp = await client.get(f'https://api.example.com/p/{symbol}')
return {'symbol': symbol, 'data': resp.json()}
return {'queued': False, 'reason': 'backpressure'}
return {'queued': True, 'depth': queue.qsize()}

Interactive Tools for This Topic

FAQ

Does `lifespan` modify its input?
No — a new value is constructed for the result and the arguments are never written to.
Which packages must be installed first?
Yes. The imports resolve to `fastapi`, `asyncio` and `httpx`, which the package manager must provide.