Depends

FastAPI interview question · Medium difficulty

What is FastAPI's Depends() and how does dependency injection work?medium

Type
conceptual
Topic
depends
Frequency
common
Tags
FastAPI, dependency injection, Depends, middleware, auth
Answer

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.

Explanation

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.

Follow-upHow do you add JWT auth to all routes in a FastAPI router?
Follow-upWhat is the difference between middleware and Depends?
Follow-upHow does a generator dependency enable cleanup?