A dependency is a function (or class) that FastAPI runs before your endpoint; you declare it with Depends(), and its return value is passed in as an argument.
It removes repeated code (database sessions, authentication, pagination parameters, settings), keeps endpoints small, supports sub-dependencies, and makes testing easy because dependencies can be replaced.
Dependencies are resolved per request, and by default a dependency used several times in one request is evaluated once and cached.
from fastapi import Depends
from sqlalchemy.orm import Session
def get_db():
db = SessionLocal()
try:
yield db # code after yield runs after the response (cleanup)
finally:
db.close()
@app.get("/items")
def list_items(db: Session = Depends(get_db)):
return db.query(ItemRow).all()