fastapi-production
Skill2 starsChanged 28 days agoApache-2.0View on GitHub
Architects, builds, and reviews production-grade async FastAPI backends with Pydantic v2, lifespan context management, JWT auth, dependency injection, and health probes.
2 other projects use a version of this.
Adopted by
Most recently taken up by
- 17tayyy/fastapi-production-rulestheir own version, first seen Sep 25, 2026
- MaheshAwasare/claude-skills-protheir own version, first seen May 4, 2026
Other versions2 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 2
- 17tayyy/fastapi-production-rules★ 3same name
- MaheshAwasare/claude-skills-pro★ 1same name
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 repository108 other files it gives its agents.
- AGENTS.mdAGENTS.md
- everything-gemini-maintainerSkill
- adversarial-fuzz-generatorSkill
- agent-evalsSkill
- ai-first-engineeringSkill
- alloydb-omni-vectorSkill
- apache-kafka-streamsSkill
- api-craftsmanSkill
- architecture-designerSkill
- argon-3d-game-engineSkill
- argon-3d-scene-architectSkill
- argon-procedural-asset-generatorSkill
- argon-visual-critique-loopSkill
- argo-workflowsSkill
- autonomous-incident-healerSkill
- axum-web-serviceSkill
- bigquery-vector-searchSkill
- browser-qa-testerSkill
- chromadb-vector-storeSkill
- cilium-ebpf-networkingSkill
- clickhouse-analyticsSkill
- cloud-deploy-canarySkill
- cloudflare-r2-object-storageSkill
- cloudflare-workersSkill
- cloud-run-agentsSkill
- context-cachingSkill
- context-distillation-compressorSkill
- context-warmerSkill
- continuous-learningSkill
- cost-oracle-finopsSkill
- cross-repo-swarm-syncSkill
- cve-remediation-orchestratorSkill
- database-architectSkill
- dataproc-spark-analyticsSkill
- dbt-transformationSkill
- debezium-cdcSkill
- devops-pipelineSkill
- distributed-rate-limitingSkill
- docker-compose-orchestratorSkill
- duckdb-local-olapSkill
- dynamic-thinking-allocationSkill
- ebpf-microvm-sandboxSkill
- ebpf-sandbox-enforcerSkill
- elephant-goldfish-modelSkill
- envoy-ai-gatewaySkill
- ephemeral-swarm-orchestratorSkill
- fullstack-nextjsSkill
- game-audio-synthesizerSkill
- game-studioSkill
- gemini-function-callingSkill
- gemini-groundingSkill
- gemini-live-audio-transcriberSkill
- gemini-live-multimodalSkill
- gemini-live-screen-visionSkill
- gemini-multimodalSkill
- genetic-prompt-cross-pollinatorSkill
- git-craftsmanSkill
- github-opsSkill
- google-axSkill
- google-flow-orchestratorSkill
- The first 60 shown.
The file
We split this skill into the rules it gives an agent
1 rule. About 0 are common, 0 are distinctive, and 1 is very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
1
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 38
Avoid deprecated @app.on_event("startup") and @app.on_event("shutdown").
≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
FastAPI Production Architect
This skill guides building high-performance, asynchronous REST APIs with FastAPI, adhering to production standards, strict type safety with Pydantic v2, clean dependency injection, and cloud-native observability.
🏗️ Production Directory Layout
app/
├── api/
│ ├── deps.py # Shared dependencies (DB sessions, current user, rate limiters)
│ └── v1/
│ ├── router.py # Root v1 router aggregating feature endpoints
│ └── endpoints/
│ ├── auth.py # Authentication & token renewal
│ └── users.py # User management endpoints
├── core/
│ ├── config.py # Pydantic BaseSettings environment validation
│ ├── database.py # Async SQLAlchemy engine & session factory
│ └── security.py # JWT encoding/decoding & Argon2/bcrypt hashing
├── models/ # SQLAlchemy ORM database models
├── schemas/ # Pydantic v2 request/response schemas
├── services/ # Pure domain business logic
└── main.py # FastAPI application initialization & lifespan⚡ Core Patterns
1. Lifespan State Management
Avoid deprecated @app.on_event("startup") and @app.on_event("shutdown"). Use modern async context lifespans:
from contextlib import asynccontextmanager
from fastapi import FastAPI
from app.core.database import engine
from app.core.redis import init_redis_pool, close_redis_pool
@asynccontextmanager
async def lifespan(app: FastAPI):
# Startup: Initialize connection pools, caches, and telemetry
app.state.redis = await init_redis_pool()
try:
yield
finally:
# Shutdown: Gracefully drain connections
await close_redis_pool(app.state.redis)
await engine.dispose()
app = FastAPI(title="Production Service", lifespan=lifespan)2. Pydantic v2 Request & Response Schemas
Enforce strict validation, immutable attributes where appropriate, and forbid undeclared payloads:
from pydantic import BaseModel, ConfigDict, EmailStr, Field
class UserBase(BaseModel):
model_config = ConfigDict(
from_attributes=True,
extra="forbid",
str_strip_whitespace=True,
)
email: EmailStr
is_active: bool = True
class UserCreate(UserBase):
password: str = Field(min_length=8, max_length=128)
class UserResponse(UserBase):
id: int3. Dependency Injection & Database Sessions
Inject asynchronous SQLAlchemy sessions using an async_sessionmaker generator yielding into FastAPI's Depends:
from collections.abc import AsyncGenerator
from fastapi import Depends
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.database import async_session_factory
async def get_db_session() -> AsyncGenerator[AsyncSession, None]:
async with async_session_factory() as session:
try:
yield session
await session.commit()
except Exception:
await session.rollback()
raise4. JWT Authentication & Permission Guards
from typing import Annotated
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from app.schemas.user import UserResponse
from app.services.auth import decode_jwt_token
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/v1/auth/token")
async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]) -> UserResponse:
user = await decode_jwt_token(token)
if not user or not user.is_active:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authentication credentials",
headers={"WWW-Authenticate": "Bearer"},
)
return user5. Standardized Problem Details Error Envelope (RFC 7807)
from fastapi import Request
from fastapi.responses import JSONResponse
async def global_exception_handler(request: Request, exc: Exception) -> JSONResponse:
return JSONResponse(
status_code=500,
content={
"type": "https://errors.example.com/internal-server-error",
"title": "Internal Server Error",
"status": 500,
"detail": "An unexpected error occurred. Please contact engineering support.",
"instance": str(request.url.path),
},
)6. Kubernetes Liveness & Readiness Probes
Expose separate endpoints for orchestrator checks:
@app.get("/healthz/liveness", tags=["Health"])
async def liveness_check():
return {"status": "ok"}
@app.get("/healthz/readiness", tags=["Health"])
async def readiness_check(db: AsyncSession = Depends(get_db_session)):
await db.execute(text("SELECT 1"))
return {"status": "ready"}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.

