fastapi-patterns
Use when building or reviewing FastAPI backends: routers, dependency injection, Pydantic models, async patterns, authentication, middleware
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
菜单
Use when building or reviewing FastAPI backends: routers, dependency injection, Pydantic models, async patterns, authentication, middleware
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
基于 SOC 职业分类
Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when AI agents perform most implementation work and humans enforce quality and risk controls.
REST API design patterns including resource naming, status codes, pagination, filtering, error responses, versioning, and rate limiting for production APIs.
Deployment workflows, CI/CD pipeline patterns, Docker containerization, health checks, rollback strategies, and production readiness checklists for web applications. Use when setting up deployment infrastructure or planning releases.
Use when generating or validating the ExecutionPlan JSON that the orchestrator must produce before spawning any agents
Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, artifacts, posters, or applications (examples include websites, landing pages, dashboards, React components, HTML/CSS layouts, or when styling/beautifying any web UI). Generates creative, polished code and UI design that avoids generic AI aesthetics.
Research-before-coding workflow. Search for existing tools, libraries, and patterns before writing custom code. Systematizes the "search for existing solutions before implementing" approach. Use when starting new features or adding functionality.
| name | fastapi-patterns |
| description | Use when building or reviewing FastAPI backends: routers, dependency injection, Pydantic models, async patterns, authentication, middleware |
app/
├── main.py ← app factory, middleware, lifespan
├── api/
│ ├── deps.py ← shared dependencies (db, auth)
│ └── v1/
│ ├── router.py ← includes all sub-routers
│ └── endpoints/
│ ├── auth.py
│ └── users.py
├── core/
│ ├── config.py ← Settings via pydantic-settings
│ └── security.py ← password hashing, JWT
├── models/
│ └── user.py ← SQLAlchemy models
├── schemas/
│ └── user.py ← Pydantic request/response schemas
└── services/
└── user_service.py ← business logic (no DB calls here)
from contextlib import asynccontextmanager
from fastapi import FastAPI
@asynccontextmanager
async def lifespan(app: FastAPI):
# startup
await db.connect()
yield
# shutdown
await db.disconnect()
def create_app() -> FastAPI:
app = FastAPI(lifespan=lifespan)
app.include_router(api_router, prefix="/api/v1")
return app
# deps.py — reusable dependencies
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBearer
security = HTTPBearer()
async def get_current_user(
token: str = Depends(security),
db: AsyncSession = Depends(get_db),
) -> User:
payload = verify_token(token.credentials)
user = await db.get(User, payload["sub"])
if not user:
raise HTTPException(status_code=401, detail="User not found")
return user
# Usage in endpoint
@router.get("/me")
async def get_me(user: User = Depends(get_current_user)):
return user
from pydantic import BaseModel, EmailStr, field_validator
from datetime import datetime
class UserCreate(BaseModel):
email: EmailStr
password: str
@field_validator("password")
@classmethod
def password_strength(cls, v: str) -> str:
if len(v) < 8:
raise ValueError("Password must be at least 8 characters")
return v
class UserResponse(BaseModel):
id: int
email: str
created_at: datetime
model_config = {"from_attributes": True}
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import DeclarativeBase
engine = create_async_engine(settings.DATABASE_URL)
class Base(DeclarativeBase):
pass
async def get_db():
async with AsyncSession(engine) as session:
yield session
from fastapi import Request
from fastapi.responses import JSONResponse
class AppError(Exception):
def __init__(self, message: str, status_code: int = 400):
self.message = message
self.status_code = status_code
@app.exception_handler(AppError)
async def app_error_handler(request: Request, exc: AppError):
return JSONResponse(
status_code=exc.status_code,
content={"error": exc.message}
)
Depends() for all shared state — never use globalsservices/, not in endpointsasync def for endpoints that do I/Oresponse_model