Dependency Injection

What is a Dependency?

A dependency is a function FastAPI calls before your endpoint, passing its return value in. Use dependencies for anything several endpoints share: pagination, the current user, a database session, settings.

Example

from typing import Annotated
from fastapi import Depends, FastAPI

app = FastAPI()

def pagination(skip: int = 0, limit: int = 10):
    return {"skip": skip, "limit": min(limit, 50)}

Page = Annotated[dict, Depends(pagination)]

@app.get("/courses")
def courses(page: Page):
    return {"courses_page": page}

@app.get("/jobs")
def jobs(page: Page):
    return {"jobs_page": page}

Requests and responses

GET /courses?skip=10&limit=5
→ 200 {"courses_page": {"skip": 10, "limit": 5}}
GET /jobs?limit=500
→ 200 {"jobs_page": {"skip": 0, "limit": 50}}

Dependencies Can Depend on Dependencies

Example

FastAPI resolves the whole chain, and each dependency runs once per request even if used several times:

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

app = FastAPI()
TOKENS = {"token-asha": {"name": "Asha", "role": "admin"}}

def get_current_user(authorization: Annotated[str | None, Header()] = None):
    user = TOKENS.get((authorization or "").removeprefix("Bearer "))
    if not user:
        raise HTTPException(status_code=401, detail="Not authenticated")
    return user

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

@app.get("/admin/stats")
def stats(admin: Annotated[dict, Depends(require_admin)]):
    return {"hello": admin["name"], "users": 1280}

Requests and responses

GET /admin/stats
→ 200 {"hello": "Asha", "users": 1280}
GET /admin/stats
→ 401 {"detail": "Not authenticated"}