Dependency Injection in FastAPI

Difficulty: Intermediate

Question

How does FastAPI's dependency injection system work? What are its benefits?

Answer

FastAPI's DI system uses the `Depends()` function. Dependencies are regular functions or classes that FastAPI calls before the path operation function, injecting their return values.

How it works: 1. Declare a dependency function 2. Use `Depends(dependency_fn)` as a default value in the path operation's parameters 3. FastAPI calls the dependency, resolves nested dependencies recursively, and passes results to the path operation

Benefits: - Code reuse across multiple routes - Automatic handling of shared logic (auth, DB sessions, pagination) - Easy testing - dependencies can be overridden - Dependency caching within a request (same instance per request by default)

Code examples

Dependency injection example

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

app = FastAPI()

# Simple dependency
def get_pagination(skip: int = 0, limit: int = 10):
    return {"skip": skip, "limit": limit}

# Auth dependency
def get_current_user(token: str):
    if token != "secret":
        raise HTTPException(status_code=401, detail="Invalid token")
    return {"user": "alice"}

# Using Annotated (recommended in FastAPI 0.95+)
Pagination = Annotated[dict, Depends(get_pagination)]
CurrentUser = Annotated[dict, Depends(get_current_user)]

@app.get("/items")
def list_items(pagination: Pagination, user: CurrentUser):
    return {"user": user, pagination}

Key points

Concepts covered

Depends, dependency injection, reusability, scoping