python-fastapi
FastAPI development with Pydantic v2, async SQLAlchemy, dependency injection, and production patterns
SKILL.mdpkg/skills/lang/python-fastapi/SKILL.md
GitHubRole
Expert FastAPI developer specializing in async Python APIs, Pydantic validation, dependency injection, and high-performance REST services. Builds production-grade APIs with proper lifespan management, structured error handling, and clean dependency graphs.
Instructions
Response Format
- App Bootstrap: Use
lifespancontext manager for startup/shutdown; initialize DB connections and close them cleanly - Pydantic Models: Use
ConfigDict(strict=True)for input; useConfigDict(from_attributes=True)for ORM output; always define field constraints withField(...) - Dependency Injection: Define
Dependsfunctions for DB sessions and services; compose dependencies to build service instances - Route Definitions: Use
status_codeparameter; useresponse_modelto control output serialization; usetagsfor OpenAPI grouping - Error Handling: Define a custom
AppExceptionwith structured code/message; register@app.exception_handlerto produce consistent JSON error responses - Async SQLAlchemy: Use
sqlalchemy[asyncio]withasyncpg; useasync_sessionmaker; useselect()statements, never legacy Query API - Router Organization: Use
APIRouterper domain withprefixandtags; register routers on the main app - Background Work: Use
BackgroundTasksfor fire-and-forget; useasyncio.create_taskor a queue for heavier workloads
Edge Cases
If a synchronous library must be called inside an async route: Run it with asyncio.to_thread or run_in_executor to avoid blocking the event loop.
If validation errors need custom messages: Override Pydantic field validators with @field_validator; register a RequestValidationError handler to unify error format.
If the dependency graph becomes deep: Flatten with intermediate provider functions; avoid nesting Depends more than two levels.
If authentication is required: Use OAuth2PasswordBearer or a custom HTTPBearer scheme; inject the current user via a dedicated dependency.
If large file uploads are needed: Use UploadFile with streaming reads; never load the full file into memory.
If OpenAPI docs need customization: Set openapi_tags, summary, and description on routes; use openapi_extra for vendor extensions.
If response caching is needed: Add a caching middleware or use starlette-cache; set appropriate Cache-Control headers.