Back to Rules
FastAPI95% popularity

FastAPI Dependency Injection Pattern

Use FastAPI's dependency injection system for authentication, database sessions, and shared business logic.

Sebastián RamírezUpdated Feb 20, 2024

Overview

FastAPI's dependency injection system is one of its most powerful features, enabling clean separation of concerns and promoting testability across the entire application stack. Unlike traditional approaches where dependencies are manually instantiated or passed around, FastAPI's system automatically resolves dependencies, handles their lifecycle, and ensures proper cleanup. The dependency injection pattern in FastAPI goes far beyond simple parameter passing. It integrates seamlessly with authentication systems through OAuth2PasswordBearer and custom security dependencies. Database sessions can be injected into route handlers and automatically committed on success or rolled back on exception, following the unit of work pattern. This approach ensures that database transactions are properly managed without explicit try/catch blocks in every route handler. When designing dependencies, consider the scoping strategy. Some dependencies should be scoped per-request (database sessions, authentication), while others can be singleton or per-application. FastAPI handles this through the use of generator functions with the yield statement, allowing for setup and teardown logic. This pattern is particularly powerful for managing resources like database connections, file handles, and external API clients. Testing benefits significantly from this architecture. Dependencies can be overridden with mocks or test-specific implementations, allowing route handlers to be tested in isolation without requiring a full application context. The Depends() function integrates with FastAPI's type system, enabling automatic request parsing, validation, and documentation generation. Each dependency declaration also contributes to the OpenAPI schema, making the API self-documenting and enabling automatic client generation.

Code Example

.fastapirules
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from sqlalchemy.orm import Session
from typing import Generator

from .database import get_db
from .models import User
from .auth import verify_token

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

async 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"},
    )

    payload = verify_token(token)
    if payload is None:
        raise credentials_exception

    user_id = payload.get("sub")
    if user_id is None:
        raise credentials_exception

    user = db.query(User).filter(User.id == user_id).first()
    if user is None:
        raise credentials_exception

    return user

async def require_admin(user: User = Depends(get_current_user)) -> User:
    if not user.is_admin:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Admin privileges required"
        )
    return user

More FastAPI Rules

FASTAPI
88%

FastAPI Async Database Patterns

Implement async database operations with SQLAlchemy 2.0 for high-concurrency FastAPI applications.

fastapiasyncdatabase
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from sqlalchemy.orm import declarative_base
from sqlalchemy i...
Mar 12, 2024by TiSever
View Rule
FASTAPI
86%

FastAPI WebSocket Real-time Patterns

Build real-time features with FastAPI WebSockets and connection manager patterns.

fastapiwebsocketsreal-time
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from typing import Dict,...
Mar 15, 2024by Sebastián Ramírez
View Rule
FASTAPI
84%

FastAPI Background Tasks

Handle long-running operations with BackgroundTasks and Celery for distributed task queues.

fastapibackground-taskscelery
from fastapi import FastAPI, BackgroundTasks, Depends, HTTPException
from pydantic import BaseModel, EmailStr
from sqlalchemy.orm import Session
from ...
Mar 20, 2024by Sebastián Ramírez
View Rule