Async generator dependencies let you run setup and cleanup code around your API calls. They help manage resources like database connections efficiently.
Async generator dependencies in FastAPI
async def dependency_name(): # setup code here yield resource # cleanup code here
The function must be async and use yield to separate setup and cleanup.
FastAPI runs the code before yield before the request and the code after yield after the request finishes.
async def get_db(): db = connect_to_db() try: yield db finally: db.close()
async def lifespan(): print('Start') yield print('End')
This FastAPI app uses an async generator dependency get_resource. It prints messages when setting up and cleaning up the resource. The endpoint uses the resource and returns it in JSON.
from fastapi import FastAPI, Depends app = FastAPI() async def get_resource(): print('Setup resource') yield 'resource data' print('Cleanup resource') @app.get('/') async def read_root(resource: str = Depends(get_resource)): print('Handling request') return {'data': resource}
Always use try/finally or code after yield to ensure cleanup runs.
Async generator dependencies work well with async database clients or other async resources.
FastAPI automatically handles calling the async generator before and after the request.
Async generator dependencies help manage setup and cleanup around requests.
Use async def with yield to create them.
They are great for managing resources like database connections safely.