How to use yield dependencies for resource management in FastAPI
yield in dependencies, generator dependencies, setup and teardown, database session management, context managers, exception handling in yield
Yield Dependencies for Resource Management
Dependencies that use yield instead of return run setup code before the route handler, inject the yielded value, then run teardown code after the response is sent — even if an exception occurred.
Database session pattern
from fastapi import Depends
from sqlalchemy.orm import Session
from .database import SessionLocal
def get_db():
db = SessionLocal() # setup
try:
yield db # injected into route
finally:
db.close() # teardown — always runs
@app.get("/users/")
def list_users(db: Session = Depends(get_db)):
return db.query(User).all()
The finally block guarantees the session closes regardless of whether the route raises an exception. Without yield, you would need to manage this manually in every route.
Multiple yield dependencies
A route can declare multiple yield dependencies, and each teardown runs in reverse order after the response. This mirrors how nested with statements work in Python.
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
def get_cache():
client = RedisClient()
try:
yield client
finally:
client.disconnect()
@app.get("/data")
def get_data(db=Depends(get_db), cache=Depends(get_cache)):
return {"ok": True}
FastAPI handles the lifecycle correctly. You never need to call teardown code inside route handlers.
