💉

FastAPI Depends() — Dependency Injection via Function Signatures

Injecting DB sessions, auth, pagination as function parameters

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

@app.get('/users')
def list_users(db: Session = Depends(get_db)):
    return db.query(User).all()

Depends(get_db) calls get_db() before the endpoint, injects yielded db as argument, then runs finally after response for guaranteed db.close().

Why This Design

  1. Testability — Replace get_db with mock for DB-free testing
  2. Reuse — Same Depends across endpoints eliminates duplication
  3. Nesting — Depends inside Depends. Dependency tree auto-resolved

Internals

FastAPI analyzes endpoint function signatures via inspect.signature(). Finds Depends defaults, adds them to call stack. Generators are handled like contextlib.contextmanager — splitting pre/post yield.

Key Points

1

Set Depends(func) as endpoint parameter default

2

FastAPI analyzes signature via inspect.signature() → auto-calls Depends

3

With generator (yield): pre-yield = setup, post-yield = guaranteed cleanup

4

Nesting possible — get_current_user → decode_token → oauth2_scheme

Use Cases

DB session management — auto create/close session per request Auth — separate token validation via Depends