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
Back to the full FastAPI cheat sheet