Concepts 🚀 Project 🧮 Labs
🧮 Labs / FastAPI / Dependency injection — Depends()

Dependency injection — Depends()

Share setup/teardown across routes. get_db is the classic example — opens a DB session per request.

main.py v3.1
API simulator click Simulate
Click "Simulate" to see what this FastAPI app does.
🧠 How it works

Depends(fn) — runs fn before the route, injects the yielded value, runs cleanup after. The dependency can itself have dependencies (chain). FastAPI builds a DAG. yield form (gen function) — code before yield is setup, after yield is cleanup. Cleanup runs EVEN on exception — perfect for closing DB sessions, releasing locks. Sub-dependencies: get_admin depends on get_current_user — FastAPI resolves in order. Dependencies can ALSO parse query/cookie/header params (like get_current_user does with token). Use cases: DB sessions, auth, rate limiting, pagination params, feature flags. Annotated[type, Depends(...)] (Python 3.9+) is the modern syntax.

✏️ Try these changes
  • Change 'secret123' to 'mypassword'
    → /me?token=mypassword now works
  • Add a new dependency require_admin that checks user['name'] == 'Ada'
    → admin-only routes
  • Change get_db's print to a real session: db = SessionLocal()
    → real DB session per request
  • Add a query param to get_current_user: from fastapi import Cookie; token: Optional[str] = Cookie(None)
    → token now read from cookie instead of query