3 Hours

10. Dependency Injection System

Dependency Injection

Dependency Injection (DI) is one of FastAPI's most powerful features. It allows you to define reusable components (dependencies) that can be injected into your path operations. Dependencies handle common tasks like database sessions, authentication, and request validation, keeping your endpoints clean and focused. To test these examples, save to main.py and run uvicorn main:app --reload.

What is Dependency Injection?

FastAPI Dependency Injection (Depends) Architecture Hierarchical sub-dependencies resolve as a DAG • Yield dependencies auto-close resources get_db() (Session) yield db; db.close() oauth2_scheme Extracts Bearer token get_current_user() Depends(oauth2_scheme), Depends(get_db) @app.get("/profile") async def profile(user = Depends(get_current_user))

Instead of writing the same code in every endpoint (like verifying a user token), you define a dependency function once. FastAPI then automatically calls that function and injects its result into your endpoint. This makes your code DRY, testable, and maintainable.

Python 3
from fastapi import FastAPI, Depends

app = FastAPI()

def common_parameters(q: str = None, skip: int = 0, limit: int = 100):
    return {"q": q, "skip": skip, "limit": limit}

@app.get("/items")
def get_items(commons: dict = Depends(common_parameters)):
    return commons

@app.get("/users")
def get_users(commons: dict = Depends(common_parameters)):
    return commons
Local Testing: Visit /items?q=test&skip=10&limit=50. The dependency automatically parses these query parameters.

Authentication Dependency

The most common use of dependencies is authentication. You create a dependency that validates the token and returns the current user.

Python 3
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
import jwt

app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
SECRET_KEY = "your-secret-key"
ALGORITHM = "HS256"

async def get_current_user(token: str = Depends(oauth2_scheme)):
    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: str = payload.get("sub")
        if user_id is None:
            raise credentials_exception
    except jwt.InvalidTokenError:
        raise credentials_exception
    return {"user_id": user_id}

@app.get("/users/me")
async def read_users_me(current_user: dict = Depends(get_current_user)):
    return current_user

Dependency with Database Session

Dependencies are perfect for managing database sessions. Open a session, yield it to the endpoint, then close it after.

Python 3
from fastapi import FastAPI, Depends
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, Session

engine = create_engine("sqlite:///./test.db")
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

app = FastAPI()

@app.get("/users")
def get_users(db: Session = Depends(get_db)):
    return {"message": "Would query users here"}

Dependencies with Sub-dependencies

Dependencies can call other dependencies. This creates a dependency tree that FastAPI resolves automatically.

Python 3
from fastapi import FastAPI, Depends, Query, HTTPException

app = FastAPI()

def verify_api_key(api_key: str = Query(...)):
    if api_key != "secret123":
        raise HTTPException(status_code=403, detail="Invalid API key")
    return api_key

def get_user_id(api_key: str = Depends(verify_api_key)):
    return 123

def get_user_profile(user_id: int = Depends(get_user_id)):
    return {"user_id": user_id, "name": "Alice", "role": "admin"}

@app.get("/admin")
def admin_panel(user: dict = Depends(get_user_profile)):
    return {"message": f"Welcome {user['name']}", "user": user}

Class-based Dependencies

You can also use classes as dependencies. This is useful when you need to store state or have multiple methods.

Python 3
from fastapi import FastAPI, Depends

app = FastAPI()

class Pagination:
    def __init__(self, page: int = 1, page_size: int = 10):
        self.page = page
        self.page_size = page_size

    def offset(self) -> int:
        return (self.page - 1) * self.page_size

    def limit(self) -> int:
        return self.page_size

@app.get("/items")
def get_items(pagination: Pagination = Depends()):
    return {
        "page": pagination.page,
        "page_size": pagination.page_size,
        "offset": pagination.offset(),
        "limit": pagination.limit()
    }

Dependencies for Permission Checking

Create reusable permission dependencies to enforce role-based access control.

Python 3
from fastapi import FastAPI, Depends, HTTPException, status

app = FastAPI()

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

def require_admin(current_user: dict = Depends(get_current_user)):
    if current_user["role"] != "admin":
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Admin required")
    return current_user

def require_moderator(current_user: dict = Depends(get_current_user)):
    if current_user["role"] not in ["admin", "moderator"]:
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Moderator required")
    return current_user

@app.delete("/users/{user_id}")
async def delete_user(user_id: int, admin: dict = Depends(require_admin)):
    return {"message": f"User {user_id} deleted by admin"}

@app.put("/posts/{post_id}")
async def moderate_post(post_id: int, moderator: dict = Depends(require_moderator)):
    return {"message": f"Post {post_id} moderated"}

Knowledge Check

Ready to test your understanding of 10. Dependency Injection System?

Back