FastAPI Dependency Injection
Use FastAPI's dependency injection for database sessions, auth checks, and shared service logic.
from fastapi import FastAPI, Depends, HTTPException
from typing import Annotated
app = FastAPI()
# Simulated DB session
async def get_db():
db = {"connected": True} # Replace with real session
try:
yield db
finally:
pass # Close session here
async def get_current_user(
token: str = "", # Normally from header
db=Depends(get_db),
):
if not token:
raise HTTPException(status_code=401, detail="Not authenticated")
return {"id": "user_1", "name": "Alice"}
DB = Annotated[dict, Depends(get_db)]
User = Annotated[dict, Depends(get_current_user)]
@app.get("/profile")
async def get_profile(user: User, db: DB):
return {"user": user, "db_connected": db["connected"]}Use Cases
- Database session management
- Authentication middleware
- Service layer injection
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
Dataclass with Validation
Python dataclass with __post_init__ field validation, type coercion, and descriptive error messages.
Custom Context Manager
Context managers for resource management using both class-based and decorator approaches with error handling.
Pytest Fixtures and Parametrize
Reusable pytest fixtures with scope control, parametrize for data-driven tests, and temporary resources.
Dataclasses with Post-Init Processing
Use Python dataclasses with __post_init__ for computed fields, validation, and default factories.