pythonintermediate
FastAPI Dependency Injection
Use FastAPI's dependency injection for database sessions, auth checks, and shared service logic.
pythonPress ⌘/Ctrl + Shift + C to copy
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.
pythonbeginner
Mistral AI API Client in Python
Make chat and embedding requests to Mistral AI using the official Python SDK.
Best for: European AI compliance
#mistral#llm
pythonbeginner
Dataclass with Validation
Python dataclass with __post_init__ field validation, type coercion, and descriptive error messages.
Best for: Data transfer objects
#dataclass#validation
pythonintermediate
Custom Context Manager
Context managers for resource management using both class-based and decorator approaches with error handling.
Best for: Database connection management
#context-manager#resource-management
pythonintermediate
Pytest Fixtures and Parametrize
Reusable pytest fixtures with scope control, parametrize for data-driven tests, and temporary resources.
Best for: Unit test setup
#pytest#testing