Cursor rule for FastAPI projects using Pydantic v2 schemas, SQLAlchemy 2 async_sessionmaker, lifespan cleanup, explicit commits and 409 conflict handling.
.cursor/rules/python-fastapi-development.mdc. Downloaded files need to be placed in that repository path.---
description: "Cursor rule for FastAPI projects using Pydantic v2 schemas, SQLAlchemy 2 async_sessionmaker, lifespan cleanup, explicit commits and 409 conflict handling."
globs: "**/*"
alwaysApply: false
---
# Python FastAPI Development (project setup, Pydantic v2, async SQLAlchemy)
Applies to: FastAPI services that use Pydantic v2 schemas and SQLAlchemy 2.x with an async driver (for example asyncpg).
Version baseline: checked against the FastAPI, Pydantic v2 and SQLAlchemy 2.x asyncio documentation. Examples need Python 3.10+. Read the pinned `fastapi`, `pydantic` and `sqlalchemy` versions and `requires-python`, and follow them if they differ. Pydantic v1 syntax (`class Config`, `orm_mode`, `.dict()`) is not used.
## Project structure
```
src/app/
├── api/
│ ├── deps.py # shared dependencies (DbSession, CurrentUser)
│ └── routes/
│ ├── users.py
│ └── posts.py
├── core/
│ ├── config.py # settings loaded from environment
│ └── security.py # password hashing, token helpers
├── db/
│ ├── models.py # SQLAlchemy ORM models
│ └── session.py # engine + async_sessionmaker
├── schemas/
│ └── user.py # Pydantic request/response models
├── services/
│ └── users.py # business logic, raises domain errors
└── main.py # app factory, lifespan, routers, exception handlers
```
## Pydantic v2 schemas
```python
from datetime import datetime
from pydantic import BaseModel, ConfigDict, EmailStr, Field
class UserBase(BaseModel):
email: EmailStr # requires the email-validator extra: pip install "pydantic[email]"
name: str = Field(min_length=1, max_length=100)
class UserCreate(UserBase):
password: str = Field(min_length=8)
class UserUpdate(BaseModel):
email: EmailStr | None = None
name: str | None = Field(default=None, min_length=1, max_length=100)
class UserResponse(UserBase):
model_config = ConfigDict(from_attributes=True) # read from ORM objects
id: str
created_at: datetime
```
- Use `model_dump(exclude_unset=True)` for PATCH updates, so fields the client did not send are not overwritten.
- `UserResponse` must never include `password` or `password_hash`.
## Async database session
```python
from collections.abc import AsyncIterator
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
engine = create_async_engine(settings.database_url, pool_pre_ping=True)
SessionLocal = async_sessionmaker(engine, expire_on_commit=False)
async def get_db() -> AsyncIterator[AsyncSession]:
async with SessionLocal() as session:
yield session
```
- Use `async_sessionmaker` (SQLAlchemy 2.0), not `sessionmaker(class_=AsyncSession)`. Keep `expire_on_commit=False` so attributes stay readable after commit.
- One `AsyncSession` per request. Never share a session between concurrent tasks (`TaskGroup`/`gather`).
- Commit explicitly in the write path (service or route) with `await session.commit()`, so commit failures become proper error responses. Do not rely on dependency teardown to commit.
- Avoid lazy loading in async code; it raises `MissingGreenlet`. Load relations with `selectinload(...)`/`joinedload(...)`.
- Tune pool sizes from measured load and database limits, not fixed numbers copied from examples.
## Lifespan
```python
from contextlib import asynccontextmanager
from fastapi import FastAPI
@asynccontextmanager
async def lifespan(app: FastAPI):
yield
await engine.dispose()
app = FastAPI(lifespan=lifespan)
```
## Routes
```python
from typing import Annotated
from fastapi import APIRouter, Depends, HTTPException, status
DbSession = Annotated[AsyncSession, Depends(get_db)]
router = APIRouter(prefix="/users", tags=["users"])
@router.post("/", response_model=UserResponse, status_code=status.HTTP_201_CREATED)
async def create_user(data: UserCreate, db: DbSession, admin: AdminUser) -> UserResponse:
"""Create a user. Admin only."""
if await user_service.get_by_email(db, data.email):
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="Email already registered")
return await user_service.create(db, data) # hashes the password and commits
@router.get("/{user_id}", response_model=UserResponse)
async def get_user(user_id: str, db: DbSession) -> UserResponse:
user = await user_service.get(db, user_id)
if user is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
return user
```
- Use 409 Conflict for a duplicate email, not 400. Also enforce a unique constraint in the database and translate `IntegrityError` to 409, because two concurrent requests can both pass the pre-check.
- `AdminUser` is a project dependency alias, like `DbSession`.
## Application errors
```python
from fastapi import Request
from fastapi.responses import JSONResponse
class AppError(Exception):
def __init__(self, status_code: int, detail: str) -> None:
self.status_code = status_code
self.detail = detail
@app.exception_handler(AppError)
async def app_error_handler(request: Request, exc: AppError) -> JSONResponse:
return JSONResponse(status_code=exc.status_code, content={"error": exc.detail})
```
## Verify before finishing
- Tests override `get_db` (and auth dependencies) through `app.dependency_overrides`, pointing to a test database or a fake. Cover the 201, 409, 404 and 422 paths.
- Run Alembic (or the project's migration tool) to generate a migration for model changes, and review it before applying. Never apply migrations to shared databases from the agent session.
- Run the project's `pytest`, linter and type checker.
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.
Cursor
backend
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
A team starting or modernising a FastAPI + PostgreSQL service asks Cursor to scaffold user endpoints with Pydantic v2 and SQLAlchemy 2 async sessions.
Upgrade src/app/schemas/user.py and db/session.py. They still use class Config: orm_mode = True and sessionmaker(engine, class_=AsyncSession). Then add POST /users (admin only, 409 on duplicate email) and GET /users/{id}. pydantic 2.11, sqlalchemy 2.0, asyncpg.Illustrative; not a recorded model run. Schemas use model_config = ConfigDict(from_attributes=True), and the answer notes that EmailStr needs pydantic[email]. session.py uses async_sessionmaker(engine, expire_on_commit=False) and a get_db dependency that only opens and closes the session. Commits happen explicitly in the service. A lifespan disposes the engine. POST returns 201, or 409 on a duplicate (an IntegrityError is also mapped to 409). The response model never exposes password_hash. Tests override get_db and the admin dependency.
Cursor applies project rules stored as .mdc files in .cursor/rules. Each rule's frontmatter (description, globs, alwaysApply) decides whether it is always included, attached to matching files, chosen by the agent from its description, or only used when you @-mention it. Cursor also reads AGENTS.md in the project root and subdirectories for plain-Markdown instructions.
.cursor/rules/python-fastapi-development.mdcStarting point, not a tested configuration for your repository. Attached when files matching the globs are in context (alwaysApply: false with globs). Review the instructions, adapt the file paths and run your project's existing checks.
---
description: "Python FastAPI Development: Project Setup with Pydantic v2 and Async SQLAlchemy 2 project conventions"
globs: "**/*"
alwaysApply: false
---
# Python FastAPI Development (project setup, Pydantic v2, async SQLAlchemy)
Applies to: FastAPI services that use Pydantic v2 schemas and SQLAlchemy 2.x with an async driver (for example asyncpg).
Version baseline: checked against the FastAPI, Pydantic v2 and SQLAlchemy 2.x asyncio documentation. Examples need Python 3.10+. Read the pinned `fastapi`, `pydantic` and `sqlalchemy` versions and `requires-python`, and follow them if they differ. Pydantic v1 syntax (`class Config`, `orm_mode`, `.dict()`) is not used.
## Project structure
```
src/app/
├── api/
│ ├── deps.py # shared dependencies (DbSession, CurrentUser)
│ └── routes/
│ ├── users.py
│ └── posts.py
├── core/
│ ├── config.py # settings loaded from environment
│ └── security.py # password hashing, token helpers
├── db/
│ ├── models.py # SQLAlchemy ORM models
│ └── session.py # engine + async_sessionmaker
├── schemas/
│ └── user.py # Pydantic request/response models
├── services/
│ └── users.py # business logic, raises domain errors
└── main.py # app factory, lifespan, routers, exception handlers
```
## Pydantic v2 schemas
```python
from datetime import datetime
from pydantic import BaseModel, ConfigDict, EmailStr, Field
class UserBase(BaseModel):
email: EmailStr # requires the email-validator extra: pip install "pydantic[email]"
name: str = Field(min_length=1, max_length=100)
class UserCreate(UserBase):
password: str = Field(min_length=8)
class UserUpdate(BaseModel):
email: EmailStr | None = None
name: str | None = Field(default=None, min_length=1, max_length=100)
class UserResponse(UserBase):
model_config = ConfigDict(from_attributes=True) # read from ORM objects
id: str
created_at: datetime
```
- Use `model_dump(exclude_unset=True)` for PATCH updates, so fields the client did not send are not overwritten.
- `UserResponse` must never include `password` or `password_hash`.
## Async database session
```python
from collections.abc import AsyncIterator
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
engine = create_async_engine(settings.database_url, pool_pre_ping=True)
SessionLocal = async_sessionmaker(engine, expire_on_commit=False)
async def get_db() -> AsyncIterator[AsyncSession]:
async with SessionLocal() as session:
yield session
```
- Use `async_sessionmaker` (SQLAlchemy 2.0), not `sessionmaker(class_=AsyncSession)`. Keep `expire_on_commit=False` so attributes stay readable after commit.
- One `AsyncSession` per request. Never share a session between concurrent tasks (`TaskGroup`/`gather`).
- Commit explicitly in the write path (service or route) with `await session.commit()`, so commit failures become proper error responses. Do not rely on dependency teardown to commit.
- Avoid lazy loading in async code; it raises `MissingGreenlet`. Load relations with `selectinload(...)`/`joinedload(...)`.
- Tune pool sizes from measured load and database limits, not fixed numbers copied from examples.
## Lifespan
```python
from contextlib import asynccontextmanager
from fastapi import FastAPI
@asynccontextmanager
async def lifespan(app: FastAPI):
yield
await engine.dispose()
app = FastAPI(lifespan=lifespan)
```
## Routes
```python
from typing import Annotated
from fastapi import APIRouter, Depends, HTTPException, status
DbSession = Annotated[AsyncSession, Depends(get_db)]
router = APIRouter(prefix="/users", tags=["users"])
@router.post("/", response_model=UserResponse, status_code=status.HTTP_201_CREATED)
async def create_user(data: UserCreate, db: DbSession, admin: AdminUser) -> UserResponse:
"""Create a user. Admin only."""
if await user_service.get_by_email(db, data.email):
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="Email already registered")
return await user_service.create(db, data) # hashes the password and commits
@router.get("/{user_id}", response_model=UserResponse)
async def get_user(user_id: str, db: DbSession) -> UserResponse:
user = await user_service.get(db, user_id)
if user is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
return user
```
- Use 409 Conflict for a duplicate email, not 400. Also enforce a unique constraint in the database and translate `IntegrityError` to 409, because two concurrent requests can both pass the pre-check.
- `AdminUser` is a project dependency alias, like `DbSession`.
## Application errors
```python
from fastapi import Request
from fastapi.responses import JSONResponse
class AppError(Exception):
def __init__(self, status_code: int, detail: str) -> None:
self.status_code = status_code
self.detail = detail
@app.exception_handler(AppError)
async def app_error_handler(request: Request, exc: AppError) -> JSONResponse:
return JSONResponse(status_code=exc.status_code, content={"error": exc.detail})
```
## Verify before finishing
- Tests override `get_db` (and auth dependencies) through `app.dependency_overrides`, pointing to a test database or a fake. Cover the 201, 409, 404 and 422 paths.
- Run Alembic (or the project's migration tool) to generate a migration for model changes, and review it before applying. Never apply migrations to shared databases from the agent session.
- Run the project's `pytest`, linter and type checker.
Ask for a small change to one matching file. Check the tool's loaded context or instruction view, inspect the diff for the requested convention, and run the relevant build or test. A well-formatted file does not guarantee the model follows every instruction.
Cursor's docs recommend keeping individual rules under 500 lines and splitting large rules into composable ones. Cursor's documentation states that it supports AGENTS.md in the project root and in subdirectories. Use AGENTS.md for plain-Markdown instructions you also want other tools to read, and .mdc rules when you need Cursor's scoping options (globs, description-based selection, always-apply).
Documentation checked 2026-11-05: Cursor docs: Rules
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.