Best .cursorrules for Python, FastAPI & Pydantic v2 in Cursor
A field-tested, production-grade .cursorrules specification for Python 3.11+, FastAPI routers, and Pydantic v2 schemas.
Why Conventional AI Assistance Hallucinates on FastAPI
Most AI coding assistants default to outdated Pydantic v1 patterns (e.g. @validator instead of @field_validator), mix ORM models directly into route return types, or inject blocking I/O calls directly inside async def handlers. This causes hidden production deadlocks under load.
The Golden Standard Ruleset
# Python / FastAPI Conventions
1. Type-annotate every function; require strict typing for all domain inputs.
2. One APIRouter per domain module; keep route handlers strictly under 25 lines.
3. Request and response bodies must be explicit Pydantic models; never return raw ORM objects.
4. Inject DB sessions, settings and authentication via FastAPI Depends; avoid module-level globals.
5. Catch domain exceptions with custom exception handlers; raise HTTPException only in the API boundary layer.
6. Strictly avoid blocking calls (requests, time.sleep, sync DB drivers) inside async def.
FastMCP Integration for FastAPI Developers
When giving your AI assistant live database inspection powers, integrate PgSafe MCP to verify query plans with EXPLAIN before execution. Run without cloning via uvx:
uvx --from git+https://github.com/johannschiffer/pgsafe-mcp pgsafe-mcp
Ready to connect these capabilities?
Generate your configuration file in one click with the Genesis Config Builder.