avibebuilder/claude-prime / .claude/starter-skills/backend-fastapi-python
backend-fastapi-python
UnverifiedUse this skill for any Python backend work in this project: building FastAPI endpoints, writing service functions, defining Pydantic/SQLModel schemas, running Alembic migrations, or debugging 422 errors. Essential for authentication and authorization patterns — setting up get_current_user, is_superuser checks, admin-only guards, role-based access, and dependency injection chains like Depends(). Also covers middleware, background tasks, async SQLAlchemy sessions, ORM relationship loading, and request/response design. Activate whenever the question involves Python API code, FastAPI patterns, or backend architecture in this codebase. Not for frontend, Docker, CI/CD, or infrastructure.
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 3.9 KB |
| references/auth.md | markdown | 5.5 KB |
| references/configuration.md | markdown | 3.5 KB |
| references/database.md | markdown | 3.9 KB |
| references/dependencies.md | markdown | 4.4 KB |
| references/error-handling.md | markdown | 4.7 KB |
| references/file-structure.md | markdown | 3.8 KB |
| references/middleware.md | markdown | 4.9 KB |
| references/models.md | markdown | 3.9 KB |
| references/routing.md | markdown | 4.5 KB |
| references/schemas.md | markdown | 4.3 KB |
| references/services.md | markdown | 5.1 KB |
references/middleware.md
View on GitHub# Middleware
## Middleware Types
FastAPI supports two middleware patterns:
1. **ASGI Middleware** - Lower level, more control
2. **BaseHTTPMiddleware** - Simpler, higher level
## Request ID Middleware (ASGI)
```python
# src/core/middlewares/request_id_middleware.py
from collections.abc import Callable
from contextvars import ContextVar
from src.core.utils import generate_id
# Context variable for request-scoped ID
request_id_var: ContextVar[str] = ContextVar("request_id", default="")
def get_request_id() -> str:
"""Get current request ID from context"""
return request_id_var.get()
class RequestIDMiddleware:
def __init__(self, app: Callable) -> None:
self.app = app
async def __call__(self, scope: dict, receive: Callable, send: Callable) -> None:
# Only process HTTP requests
if scope["type"] != "http":
await self.app(scope, receive, send)
return
# Get or generate request ID
headers_dict = dict(scope["headers"])
request_id = headers_dict.get(b"x-request-id")
if not request_id:
request_id = f"req_{generate_id()}".encode()
headers_dict[b"x-request-id"] = request_id
scope["headers"] = list(headers_dict.items())
# Set in context for use in handlers
request_id_var.set(request_id.decode())
await self.app(scope, receive, send)
```
## Logging Middleware (BaseHTTPMiddleware)
```python
# src/core/middlewares/logging_middleware.py
import time
from fastapi import Request
from loguru import logger
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
from starlette.responses import Response
class RequestLoggingMiddleware(BaseHTTPMiddleware):
async def dispatch(
self, request: Request, call_next: RequestResponseEndpoint
) -> Response:
request_id = request.headers.get("x-request-id", "unknown")
start_time = time.time()
# Request info
method = request.method
path = request.url.path
query = request.url.query
path_with_query = f"{path}?{query}" if query else path
# Client IP (handle proxy headers)
client_ip = request.headers.get("x-forwarded-for", "").split(",")[0].strip()
if not client_ip:
client_ip = request.client.host if request.client else "unknown"
# Log request
logger.info(
f"[{request_id}] Req: {client_ip} {method} {path_with_query}",
extra={
"request_id": request_id,
"client_ip": client_ip,
"method": method,
"path": path,
},
)
# Process request
response = await call_next(request)
# Log response
duration = time.time() - start_time
logger.info(
f"[{request_id}] Res: {response.status_code} ({duration:.3f}s)",
extra={
"request_id": request_id,
"status_code": response.status_code,
"duration": duration,
},
)
return response
```
## Registration Order
```python
# src/main.py
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from src.core.middlewares.logging_middleware import RequestLoggingMiddleware
from src.core.middlewares.request_id_middleware import RequestIDMiddleware
app = FastAPI()
# CORS first (outermost)
app.add_middleware(
CORSMiddleware,
allow_origins=settings.CORS_ORIGINS,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Custom middleware (execution order: last added = first executed)
app.add_middleware(RequestLoggingMiddleware)
app.add_middleware(RequestIDMiddleware)
```
**Execution order:**
```
Request → RequestIDMiddleware → RequestLoggingMiddleware → CORS → Route
Response ← RequestIDMiddleware ← RequestLoggingMiddleware ← CORS ← Route
```
## Using Context Variables
```python
# In exception handlers
from src.core.middlewares.request_id_middleware import get_request_id
@app.exception_handler(Exception)
async def exception_handler(request: Request, exc: Exception):
request_id = get_request_id()
logger.error(f"[{request_id}] Error: {exc}")
return JSONResponse(
status_code=500,
content={"request_id": request_id, "message": "Internal error"},
)
```
## CORS Configuration
```python
app.add_middleware(
CORSMiddleware,
allow_origins=settings.CORS_ORIGINS, # List of allowed origins
allow_credentials=True, # Allow cookies
allow_methods=["*"], # Allow all methods
allow_headers=["*"], # Allow all headers
)
```
## Best Practices
1. **Use ASGI for performance** - Lower overhead than BaseHTTPMiddleware
2. **Use BaseHTTPMiddleware for simplicity** - When you need Request/Response objects
3. **Order matters** - Last added = first executed
4. **Use context variables** - For request-scoped data (request ID, user)
5. **Log request ID everywhere** - For tracing
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| writing-skillsobra/superpowersUse when creating new skills, editing existing skills, or verifying skills work before deployment | Stars: 318k | Updated | Claude CodeCodex | Unverified | Install |
| xlsxanthropics/skillsUse this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing .xlsx, .xlsm, .xltx, .csv, or .tsv file (e.g., adding columns, computing formulas, formatting, charting, cleaning messy data); create a new spreadsheet from scratch or from other data sources; or convert between tabular file formats. Trigger especially when the user references a spreadsheet file by name or path — even casually (like "the xlsx in my downloads") — and wants something done to it or produced from it. Also trigger for cleaning or restructuring messy tabular data files (malformed rows, misplaced headers, junk data) into proper spreadsheets. The deliverable must be a spreadsheet file. Do NOT trigger when the primary deliverable is a Word document, HTML report, standalone Python script, database pipeline, or Google Sheets API integration, even if tabular data is involved. | Stars: 196k | Updated | Claude CodeCodex | Verified | Install |
| shipping-and-launchaddyosmani/agent-skillsPrepares production launches. Use when preparing to deploy to production, or when asking what needs to be in place before shipping. Use when you need a pre-launch checklist, when setting up monitoring, when planning a staged rollout, or when you need a rollback strategy. | Stars: 118k | Updated | Claude CodeCodex | Verified | Install |
| childhoodthedotmack/claude-memBabysit a shipped release after merge, publication, or deployment. Verify published packages, production behavior, installed plugins, and late CI or user reports until the observation window is clean; use babysit for PR readiness before release. | Stars: 117k | Updated | Claude CodeCodex | Unverified | Install |