What is FastAPI's Depends() and how does dependency injection work?medium
Depends() is FastAPI's dependency injection — you declare shared logic like auth or a DB session as a function and FastAPI calls it automatically before your route runs. Dependencies are composable and cached per request by default.
FastAPI resolves the full dependency tree automatically, so a dependency can itself have dependencies. The same DB session is reused across multiple Depends calls in one request unless overridden. A generator dependency using yield enables guaranteed cleanup: code before yield runs on entry, code after yield runs after the response is sent. Middleware wraps the entire app and runs on every request; Depends is per-route and can be applied at the route or router level. For auth, declare a get_current_user dependency using HTTPBearer() to extract the token, validate it, and raise 401 on failure.