Dependency Injection in FastAPI

Difficulty: Intermediate

Question

How does FastAPI's dependency injection system work with Depends(), and what problems does it solve?

Answer

FastAPI's dependency injection lets a path operation declare what it needs, such as a database session, the current user or pagination values, by adding a parameter wrapped in Depends(some_callable). For every request FastAPI resolves the whole dependency graph: it calls each dependency with values pulled from the request, caches results within that request, and passes the return values into your handler.

How resolution works

A dependency is any callable: a function, an async function or a class. FastAPI inspects its signature exactly like a handler, so a dependency can itself take query params, headers, a body or other dependencies.

  1. At startup FastAPI builds a tree of dependencies for each route.
  2. On a request, it resolves leaves first (e.g. get_token reads the Authorization header).
  3. Results flow upward (get_current_user uses the token, require_admin uses the user).
  4. Each dependency runs once per request even if several others ask for it; pass Depends(dep, use_cache=False) to opt out.
  5. If any dependency raises HTTPException, the handler never runs.

Parameters a dependency reads also appear in the OpenAPI docs, so skip and limit from a shared pagination dependency show up on every route that uses it.

Dependencies with yield

A dependency that uses yield acts like a context manager: code before yield is setup, the yielded value is injected, and code after yield is teardown. This is the standard pattern for a database session: open it, yield it, then commit or roll back and close it in finally. Wrap the yield in try/except if you want to roll back on errors raised by the handler. Do not use the yielded session inside BackgroundTasks; open a fresh one there, because teardown timing relative to the response has changed across FastAPI versions.

Where you can attach dependencies

LevelSyntaxTypical use
Parameteruser: Annotated[User, Depends(get_current_user)]You need the value
Decorator@app.get(..., dependencies=[Depends(verify_api_key)])Run a check, ignore the value
RouterAPIRouter(dependencies=[Depends(require_admin)])Protect a whole group, e.g. /admin
AppFastAPI(dependencies=[...])Global checks

Why it matters

  • Reuse: auth, pagination and tenant lookups are written once.
  • Testability: app.dependency_overrides[get_db] = get_test_db swaps real resources for fakes without touching handlers.
  • Separation of concerns: handlers contain business logic only; plumbing lives in dependencies.
  • Docs for free: dependency parameters are documented automatically.

Gotchas

  • Pass the function, do not call it: Depends(get_db), not Depends(get_db()).
  • Sync def dependencies run in the threadpool, just like sync handlers.
  • Depends() with no argument on a class-typed parameter uses the class itself as the dependency.
  • Use Annotated type aliases (CurrentUser = Annotated[User, Depends(get_current_user)]) to avoid repeating yourself; this is the style FastAPI recommends since 0.95.
Resolving a dependency chain. Each dependency feeds the next, and the handler only runs if all of them succeed.
  1. Request arrives: Authorization header and query params present.
  2. get_token: Extracts the bearer token from the header.
  3. get_current_user: Decodes the token and loads the user.
  4. require_admin: Raises 403 if the role is wrong.
  5. Path operation: Receives the resolved admin user.

Code examples

Chained, cached and yield dependencies

from typing import Annotated
from fastapi import Depends, FastAPI, Header, HTTPException, Query

app = FastAPI()

def get_db():
    db = {"connected": True}          # stand-in for SessionLocal()
    try:
        yield db                      # injected into the handler
    finally:
        db["connected"] = False       # teardown: close the session

def get_current_user(authorization: Annotated[str, Header()]):
    if authorization != "Bearer secret":
        raise HTTPException(status_code=401, detail="Invalid token")
    return {"id": 7, "role": "admin"}

def require_admin(user: Annotated[dict, Depends(get_current_user)]):
    if user["role"] != "admin":
        raise HTTPException(status_code=403, detail="Admins only")
    return user

class Pagination:                     # a class works as a dependency too
    def __init__(self, skip: int = 0, limit: Annotated[int, Query(le=100)] = 20):
        self.skip, self.limit = skip, limit

DB = Annotated[dict, Depends(get_db)]
Admin = Annotated[dict, Depends(require_admin)]

@app.get("/admin/orders")
def list_orders(db: DB, admin: Admin, page: Annotated[Pagination, Depends()]):
    return {"admin": admin["id"], "skip": page.skip, "limit": page.limit}

get_current_user runs once even though require_admin depends on it. Annotated aliases keep handler signatures short.

Overriding a dependency in tests

from fastapi.testclient import TestClient
from main import app, get_current_user

def fake_admin():
    return {"id": 1, "role": "admin"}

app.dependency_overrides[get_current_user] = fake_admin
client = TestClient(app)

def test_admin_orders():
    r = client.get("/admin/orders")
    assert r.status_code == 200
    app.dependency_overrides.clear()

dependency_overrides replaces a dependency everywhere it is used, including inside other dependencies.

Key points

  • Depends takes a callable; FastAPI calls it per request and injects the result
  • Dependencies are cached per request unless use_cache=False
  • yield dependencies give setup and teardown, ideal for DB sessions
  • Attach at parameter, decorator, router or app level
  • app.dependency_overrides is the main tool for testing

Common follow-up questions

  • How would you protect every route under /admin with one dependency?
  • What is the difference between a dependency and a middleware?
  • How do dependencies with yield handle exceptions raised in the handler?
  • How do you use a class as a dependency, and when would you?

Interview tips

  • Describe it as a per-request dependency graph with caching; that is the key insight
  • Mention dependency_overrides for testing; interviewers care about testability
  • Use Annotated in your examples to show you write current-style FastAPI

Concepts covered

Depends, dependency injection, yield dependencies, dependency caching, dependency_overrides

More FastAPI Interview questions