📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials FastAPI Dependency Injection

Dependency Injection

6 min read Quiz at the end
Inject DB sessions, auth, and settings into endpoints using FastAPI's Depends() system.

Dependency Injection

from fastapi import Depends, HTTPException, status
from sqlalchemy.orm import Session

# DB session dependency
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

# Auth dependency
def get_current_user(
    token: str = Depends(oauth2_scheme),
    db:    Session = Depends(get_db)
) -> User:
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": "Bearer"},
    )
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        user_id: int = payload.get("sub")
        if user_id is None:
            raise credentials_exception
    except JWTError:
        raise credentials_exception
    user = db.get(User, user_id)
    if not user:
        raise credentials_exception
    return user

# Use in endpoint
@app.get("/me")
def me(current_user: User = Depends(get_current_user)):
    return current_user
Topic Quiz · 3 questions

Test your understanding before moving on

1. What does Depends() provide?
💡 Depends() declares a dependency that FastAPI creates and injects before calling the endpoint.
2. Why use yield in a dependency like get_db?
💡 yield creates a generator; code before yield is setup, code after is teardown.
3. What is the benefit of Depends() over global state?
💡 Override dependencies with app.dependency_overrides in tests for easy mocking.