FastAPI Cursor Rules: Modern Python APIs Guide
Cursor rules for FastAPI development covering Pydantic models, async endpoints, dependency injection, OpenAPI documentation, and production deployment patterns.
Overview
FastAPI has revolutionized Python web development with its async-first design, high performance, and automatic OpenAPI documentation. These cursor rules enforce modern Python patterns, strict Pydantic data validation, and dependency injection to help AI assistants generate type-safe, performant APIs. Whether you're building a microservice or an AI model wrapper, these rules ensure your endpoints are well-documented, asynchronous, and production-ready.
Note:
Enforces Pydantic model validation, dependency injection patterns, OpenAPI documentation, and async endpoint best practices.
Rules Configuration
---
description: Enforces best practices for FastAPI development, focusing on Pydantic models, async endpoints, dependency injection, and OpenAPI documentation. Provides comprehensive guidelines for writing clean, performant Python APIs with proper context.
globs: **/*.py
---
# FastAPI Best Practices
You are an expert in FastAPI development and related web technologies.
You understand modern FastAPI development practices, architectural patterns, and the importance of providing complete context in code generation.
### Context-Aware Code Generation
- Provide complete endpoint context including path params, query params, request body, and response model
- Include relevant config (database URL, CORS origins) when generating application code
- Generate complete async function signatures with proper type hints and docstrings
- Document the request/response flow for each endpoint
### Project Structure
- /main.py - app entry point with FastAPI() instance and lifespan handlers
- /routers - route modules organized by domain or resource
- /schemas - Pydantic models for request validation and response serialization
- /services - business logic layer separate from route handlers
- /dependencies - reusable dependency injection functions
### Pydantic Models & Validation
- Use Pydantic BaseModel for all request and response schemas
- Use Field() with validation constraints (min_length, max_length, ge, le) on model fields
- Use Config.extra = "forbid" to reject unknown fields on input
- Use Pydantic validators (@field_validator, @model_validator) for cross-field validation
- Return Pydantic models from endpoint functions for automatic OpenAPI schema generation
### Async Endpoint Patterns
- Use async def for I/O-bound endpoints (database queries, HTTP calls, file operations)
- Return proper HTTP status codes: 200 for success, 201 for created, 204 for no content
- Use BackgroundTasks for non-critical post-response work (email, logging)
- Handle errors with HTTPException and custom exception handlers
- Use Depends() for reusable authentication, database sessions, and permissions
### Testing & Quality
- Write tests with pytest and httpx.AsyncClient for async endpoint testing
- Use dependency overrides to mock database and external services in tests
- Test validation error responses for invalid input payloads
- Run mypy for type checking and ruff for code formatting
- Generate and review OpenAPI docs at /docs for completeness
### Build & Deployment
- Use Uvicorn with Gunicorn for production async serving
- Set CORS middleware with explicit allow_origins for security
- Configure environment-specific settings with pydantic-settings BaseSettings
- Use Alembic for async database migrations with SQLAlchemy
- Add health check endpoint (/health) for monitoring and load balancers
Installation
Create fastapi.mdc in your project's .cursor/rules/ directory and paste the configuration above. Cursor and Windsurf both read .cursor/rules/ — Copilot users place it in .github/copilot-instructions.md instead.
Examples
# schemas.py — Pydantic models with validation
from pydantic import BaseModel, Field, EmailStr
from typing import Optional
class UserCreate(BaseModel):
email: EmailStr
username: str = Field(min_length=3, max_length=50)
bio: Optional[str] = Field(None, max_length=500)
class UserResponse(BaseModel):
id: int
email: EmailStr
username: str
is_active: bool
model_config = {"from_attributes": True}
# routers/users.py — Async endpoint with dependency injection
from fastapi import APIRouter, Depends, HTTPException, status
router = APIRouter(prefix="/users", tags=["users"])
@router.post("/", response_model=UserResponse, status_code=status.HTTP_201_CREATED)
async def create_user(
data: UserCreate,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(get_current_user),
):
existing = await db.execute(select(User).where(User.email == data.email))
if existing.scalar_one_or_none():
raise HTTPException(status_code=409, detail="Email already registered")
user = User(**data.model_dump())
db.add(user)
await db.commit()
await db.refresh(user)
return user
Related Resources
Related Articles
Ruby Cursor Rules: AI-Powered Development Best Practices
Cursor rules for Ruby that enforce Rails best practices, modern Ruby 3+ features, and clean code principles with AI assistance for secure, maintainable, production-ready applications.
Bash/Shell Cursor Rules: Scripting and Automation Guide
Cursor rules for Bash and shell scripting covering POSIX compliance, error handling, command-line tools, and automation patterns for efficient terminal workflows.
Elixir Cursor Rules: AI-Powered Development Best Practices
Cursor rules for Elixir development enforcing official style guides, modern Elixir 1.12+ features, and clean code principles with AI assistance for production-ready code.