Production-Ready Rule
•
**/*.py, api/**/*.py, routers/**/*.py
FastAPI & Pydantic v2 Microservices .cursorrules (.mdc)
Production-grade .cursorrules and .cursor/rules/*.mdc configuration for FastAPI and Pydantic v2. Enforce dependency injection, async I/O discipline, and strict typing.
.cursor/rules/python-fastapi.mdc
---
description: Python FastAPI, Pydantic v2, and async service engineering standards
globs: **/*.py, api/**/*.py, routers/**/*.py
alwaysApply: false
---
# FastAPI & Python Standards
## Type Safety & Schema Validation
- All request bodies, path parameters, and responses MUST be declared with Pydantic v2 BaseModel.
- Always use Python 3.11+ type union syntax (X | None instead of Optional[X]).
- Use Pydantic v2 syntax: .model_dump() instead of deprecated .dict(), and @field_validator.
- Always declare explicit response_model on endpoints or use typed return annotations.
## Routing & Dependency Injection
- Organize routes using APIRouter with clear tags and prefix definitions.
- Inject database sessions and current user auth contexts using Depends().
- Never use global database connections or unmanaged session singletons.
## Async & Concurrency Discipline
- Use async def for I/O-bound operations (database queries, external HTTP calls via httpx).
- Use standard def for synchronous CPU-bound operations or libraries without async support (e.g. pandas, Pillow).
- Always raise HTTPException(status_code=..., detail=...) with standard status constants.
⭐
Using this rule in your open-source project? Reference in your README:
https://cursor.pacebowl.com/rules/python-fastapi
Frequently Asked Questions & Implementation Notes
How does this rule enforce Pydantic v2 migration patterns?
It explicitly flags and forbids deprecated v1 methods like .dict() and @validator, directing the AI to emit .model_dump(), .model_dump_json(), and @field_validator exclusively.
Does this prevent blocking synchronous calls in async endpoints?
Yes, the rule instructs the LLM to separate synchronous CPU-bound logic into standard def or run via starlette run_in_threadpool, while keeping async def strictly for non-blocking I/O.