Python & FastAPI AI Agent Rules & Cursorrules
Enforce modern Python 3.12, async FastAPI, and Pydantic v2 patterns in AI agents.
Prevent AI models from generating legacy Python 2/3.8 patterns. Enforce Python 3.12 type hints, Pydantic v2 settings, FastAPI dependency injection, and async database sessions.
Configuration Workbench
Select your agent format below to preview, copy, or download the configuration file.
# Python 3.12 & FastAPI Cursor Rules
You are a Principal Python Backend Architect.
## Core Invariants
- Python: 3.12+. Use modern syntax: 'X | Y' instead of 'Union[X, Y]', 'X | None' instead of 'Optional[X]'.
- Framework: FastAPI with Pydantic v2.
- ORM / Database: Async SQLAlchemy 2.0 or SQLModel.
- Typing: 100% type-annotated code passing 'mypy --strict'.
## FastAPI Best Practices
- Dependency Injection: Use 'Annotated[Session, Depends(get_db)]' for database sessions and auth.
- Async correctness: Use 'async def' for endpoints doing async I/O. Use 'def' for synchronous tasks.
- Error handling: Raise 'HTTPException' with detailed RFC-compliant detail messages.
- Schema separation: Separate Request DTOs from Response DTOs. Never return raw database models directly.Pro-tip: Place this file directly in the root directory of your Python 3.12, FastAPI & Pydantic v2 project. AI agents like Cursor Composer, Claude Code, and GitHub Copilot will read it automatically on initialization.
Architectural Principles Enforced
When this configuration file is loaded into Cursor or Claude Code, the agent strictly enforces the following design invariants:
Use modern Python 3.10+ type hinting: `list[str]` instead of `typing.List[str]`, `str | None` instead of `Optional[str]`.
Use Pydantic v2 with `model_validator` and `field_validator` (avoid deprecated Pydantic v1 syntax).
Use FastAPI `Depends()` for all service layers, authentication, and database session injection.
Always use `async def` for I/O bound endpoints; use standard `def` for CPU-bound computations.
Follow Ruff / Black formatting guidelines and enforce strict type checking with mypy / pyright.
Installation & Repository Setup
Place in project root as `.cursorrules` or `CLAUDE.md`.
Verified Agent Behavior Examples
Observe how the AI agent responds when prompted under these active rules.
Frequently Asked Questions
Why should I use Annotated with Depends in FastAPI?
Using `Annotated[Type, Depends(...)]` allows you to declare dependencies cleanly while keeping function signatures testable, type-safe, and compatible with static analyzers like mypy.