0
0
FastAPIframework~5 mins

Async generator dependencies in FastAPI

Choose your learning style9 modes available
Introduction

Async generator dependencies let you run setup and cleanup code around your API calls. They help manage resources like database connections efficiently.

When you need to open a database connection before handling a request and close it after.
When you want to start a session or transaction before processing and ensure it ends properly.
When you need to acquire and release external resources like files or network connections.
When you want to run some code before and after each API call automatically.
When you want to clean up resources even if an error happens during request handling.
Syntax
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.

Examples
Open a database connection before the request and close it after.
FastAPI
async def get_db():
    db = connect_to_db()
    try:
        yield db
    finally:
        db.close()
Simple async generator that prints messages before and after the request.
FastAPI
async def lifespan():
    print('Start')
    yield
    print('End')
Sample Program

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.

FastAPI
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}
OutputSuccess
Important Notes

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.

Summary

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.