Dependency Injection in Python
From the FastAPI cheat sheet ยท Dependencies ยท verified Nov 2026
Dependency Injection
Share logic across endpoints using Depends().
python
from typing import Annotated
from fastapi import Depends
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
@app.get("/items/")
def read_items(db: Annotated[Session, Depends(get_db)]):
return db.scalars(select(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
Continue with FastAPI
Save the full cheat sheet or work through every related task.