fastapi-patterns
Skill4 starsChanged 5 months agoMITView on GitHub
Modern FastAPI 0.111+ production patterns for Python services — async lifespan, Pydantic v2 schemas, dependency injection, middleware ordering, structured exception handlers, router composition. Use for FastAPI endpoint design, service composition, API contract evolution, and migrating from `@app.on_event` / Pydantic v1.
19 other projects use a version of this.
Adopted by
Most recently taken up by
- skateddu/claude-code-python-setuptheir own version, first seen Nov 8, 2026
- ahmadvahidi/skill-atlastheir own version, first seen Nov 8, 2026
- ControllableModel/SWE-Skills-Benchtheir own version, first seen Nov 8, 2026
- ku5ic/claude-kittheir own version, first seen Nov 4, 2026
- renepf/claude-skillstheir own version, first seen Oct 25, 2026
- davidanthonyn/claude-skillstheir own version, first seen Oct 20, 2026
Used with
Projects with it also use redis-patterns, typescript-patterns and 10 more.
Other files people use alongside this one.
Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
nek1987Skillredis-patterns
Upstash Redis patterns for caching and rate limiting.
Also in 6 projects that use this
cohen-lielSkilltypescript-patterns
TypeScript best practices and patterns. Use when writing TypeScript code, defining types, working with generics, or converting JavaScript to TypeScript.
Also in 3 projects that use this
LangChainSkilldocker-patterns
Best practices for Docker containerization and multi-stage builds
Also in 7 projects that use this
mstuder-slalomSkillgolang-patterns
Idiomatic Go patterns, best practices, and conventions for building robust, efficient, and maintainable Go applications.
Also in 5 projects that use this
mstuder-slalomSkilldjango-security
Django security best practices, authentication, authorization, CSRF protection, SQL injection prevention, XSS prevention, and secure deployment configurations.
Also in 4 projects that use this
xenitV1Skillpython-patterns
Python development principles and decision-making. Framework selection, async patterns, type hints, project structure. Teaches thinking, not copying.
Also in 6 projects that use this
- +1 more from mstuder-slalom
Other versions19 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 19
- Fmarzochi/EGC★ 61same name
- skateddu/claude-code-python-setup★ 28same name
- ControllableModel/SWE-Skills-Bench★ 8same name
- gongyijie85/dsh-ecc★ 8same name
- hieutrtr/ai1-skills★ 8same name
- peopleforrester/claude-dotfiles★ 3same name
- bjornjee/skills★ 2same name
- ku5ic/claude-kit★ 2same name
- ronmkr/PromptBook★ 2same name
- seikaikyo/dash-skills★ 2same name
9 more not listed
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository101 other files it gives its agents.
- ai-video-understandingSkill
- apple-foundation-modelsSkill
- arch-dddSkill
- arch-decision-recordsSkill
- arch-diagramsSkill
- arch-eventsSkill
- arch-mvp-roadmapSkill
- arch-python-modernSkill
- aws-app-runnerSkill
- aws-cicd-patternsSkill
- aws-security-hardeningSkill
- azure-functions-python-v2Skill
- azure-identity-m2m-authSkill
- azure-service-bus-messagingSkill
- azure-workflow-execution-modelsSkill
- caddy-tls-proxySkill
- compliance-frameworksSkill
- design-system-workflowSkill
- dev-debugging-strategiesSkill
- dev-standardsSkill
- docker-python-poetrySkill
- docker-pythonSkill
- ffmpeg-laravel-videoSkill
- formik-yup-react-nativeSkill
- frontend-accessibilitySkill
- frontend-angular-aiSkill
- frontend-angularSkill
- frontend-angular-toolingSkill
- frontend-design-systemsSkill
- frontend-material-chatSkill
- frontend-material-design-3Skill
- frontend-svelteSkill
- gcp-cicd-patternsSkill
- gcp-cloud-runSkill
- gcp-cloudsql-infrastructureSkill
- gcp-finopsSkill
- gcp-observabilitySkill
- gcp-security-hardeningSkill
- github-actions-cicdSkill
- healthkit-biofeedbackSkill
- infra-terraformSkill
- ios-app-qualitySkill
- ios-audio-hapticsSkill
- jest-nestjs-testingSkill
- langchain-azure-openai-patternsSkill
- laravel-auth-hardeningSkill
- laravel-ci-mysqlSkill
- laravel-mix-webpackSkill
- laravel-modern-patternsSkill
- laravel-pint-patternsSkill
- laravel-s3-storageSkill
- laravel-sail-dockerSkill
- mobile-app-deploymentSkill
- mobile-e2e-testingSkill
- mobile-offline-syncSkill
- mobile-push-notificationsSkill
- mobile-video-uploadSkill
- mongodb-asyncmongoclient-patternsSkill
- mongodb-atlas-patternsSkill
- nestjs-patternsSkill
- The first 60 shown.
The file
Files
FastAPI Production Patterns
Modern FastAPI 0.111+ patterns for production microservices. This skill covers the patterns that change across versions and trip up teams: lifespan replacing @app.on_event, Pydantic v2 schema patterns, Depends() caching/scoping, middleware LIFO order, and structured error handling.
When to use
- Designing or refactoring a FastAPI service (new endpoints, lifespan resources, DI graph)
- Migrating from
@app.on_event→lifespanor Pydantic v1 → v2 - Debugging "CORS missing on 500 errors" or "blocking async endpoint" issues
- Evolving API contracts (versioning, OpenAPI customization, response schemas)
For modern Python idioms throughout, see arch-python-modern. For service-layer separation (app/routers/ ↔ app/services/ ↔ app/crud/), see arch-ddd.
Core patterns
| Pattern | One-line rule |
| Lifespan | @asynccontextmanager async def lifespan(app) — startup before yield, shutdown after; reverse-order resource teardown |
Depends() | Cached once per request; use Annotated[T, Depends(get_x)] aliases at module level |
| Pydantic v2 | model_config = ConfigDict(...); @field_validator/@model_validator; model_dump() not .dict() |
| Schema separation | Three classes per resource: XCreate (request), XRead (response), XUpdate (PATCH, all optional) |
| Middleware order | LIFO — add_middleware last = runs first on request. CORSMiddleware sits outermost so OPTIONS preflight reaches it before auth runs and 500 responses still pass through it (otherwise CORS headers are lost — see reference.md) |
| Exception handlers | Register @app.exception_handler(Exception) so errors pass through CORS layer (else 500s lose CORS headers) |
| Router composition | APIRouter(prefix=..., tags=..., dependencies=[Depends(Auth())]) — apply auth at router, not per-endpoint |
| Test overrides | app.dependency_overrides[get_db] = fake_db; clearing in fixture teardown prevents cross-test leakage when the app instance persists across tests |
Quick reference
# Lifespan (replaces @app.on_event)
@asynccontextmanager
async def lifespan(app: FastAPI):
create_mongo_client() # mandatory — let exception abort startup
await initialize_http_client()
yield
shutdown_http_client() # reverse order
shutdown_mongo_client()
app = FastAPI(lifespan=lifespan)
# Pydantic v2 schemas
class ProductCreate(BaseModel):
model_config = ConfigDict(extra="forbid")
name: str
sku: str
class ProductRead(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: str
name: str
sku: str
created_at: datetime
# Dependency injection (Annotated alias style)
DbSession = Annotated[AsyncSession, Depends(get_db)]
@router.get("/products", response_model=list[ProductRead])
async def list_products(db: DbSession): ...Anti-patterns (top 4)
- Blocking I/O in
async def→ wrap withawait asyncio.to_thread(...)or usehttpx.AsyncClient - Mutable default in
Depends(tags: list = []) → useNone+ reassign, orQuery(default_factory=list) - Single schema for request + response → split into
XCreate/XRead/XUpdate - Missing HTTP client timeouts →
httpx.AsyncClient(timeout=httpx.Timeout(connect=2.0, read=5.0))
See reference.md for the full pattern catalogue and examples.md for project-grounded implementations.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

