SKILL.md--- name: fastapi-patterns description: FastAPI patterns for async APIs, dependency injection, Pydantic request and response models, OpenAPI docs, tests, security, and production readiness. origin: community --- # FastAPI Patterns Production-oriented patterns for FastAPI services. ## When to Use - Building or reviewing a FastAPI app. - Splitting routers, schemas, dependencies, and database access. - Writing async endpoints that call a database or external service. - Adding authentication, authorization, OpenAPI docs, tests, or deployment settings. - Checking a FastAPI PR for copy-pasteable examples and production risks. ## How It Works Treat the FastAPI app as a thin HTTP layer over explicit dependencies and service code: - `main.py` owns app construction, middleware, exception handlers, and router registration. - `schemas/` owns Pydantic request and response models. - `dependencies.py` owns database, auth, pagination, and request-scoped dependencies. - `services/` or `crud/` owns business and persistence operations. - `tests/` overrides dependencies instead of opening production resources. Prefer small routers and explicit `response_model` declarations. Keep raw ORM objects, secrets, and framework globals out of response schemas. ## Project Layout ```text app/ |-- main.py |-- config.py |-- dependencies.py |-- exceptions.py |-- api/ | `-- routes/ | |-- users.py | `-- health.py |-- core/ | |-- security.py | `-- middleware.py |-- db/ | |-- session.py | `-- crud.py |-- models/ |-- schemas/ `-- tests/ ``` ## Application Factory Use a factory so tests and workers can build the app with controlled settings. ```python from contextlib import asynccontextmanager from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from app.api.routes import health, users from app.config import settings from app.db.session import close_db, init_db from app.exceptions import register_exception_handlers @asynccontextmanager async def lifespan(app: FastAPI): await init_db() yield await close_db() def create_app() -> FastAPI: app = FastAPI( title=settings.api_title, version=settings.api_version, lifespan=lifespan, ) app.add_middleware( CORSMiddleware, allow_origins=settings.cors_origins, allow_credentials=bool(settings.cors_origins), allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE"], allow_headers=["Authorization", "Content-Type"], ) register_exception_handlers(app) app.include_router(health.router, prefix="/health", tags=["health"]) app.include_router(users.router, prefix="/api/v1/users", tags=["users"]) return app app = create_app() ``` Do not use `allow_origins=["*"]` with `allow_credentials=True`; browsers reject that combination and Starlette disallows it for credentialed requests. ## Pydantic Schemas Keep request, update, and response models separate. ```python from datetime import datetime from typing import Annotated from uuid import UUID