Dependency Injection in Python
From the FastAPI cheat sheet ยท Dependencies ยท verified Jul 2026
Dependency Injection
Share logic across endpoints using Depends().
python
from fastapi import Depends
async def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
@app.get("/items/")
async def read_items(db: Session = Depends(get_db)):
return db.query(Item).all()๐ก Dependencies with yield run cleanup code after the response โ perfect for DB sessions
โก Sub-dependencies chain automatically: get_admin_user โ get_current_user โ oauth2_scheme
๐ Use Depends() without arguments on a class to use it directly as a dependency
๐ข Global dependencies apply to every route โ great for API key verification
dependenciesdependsinjection