Cursor rules for designing a FastAPI HTTP contract with separate input and output models, accurate status codes, one error shape, bounded pagination and reviewed OpenAPI.
.cursor/rules/fastapi-api-design.mdc. Downloaded files need to be placed in that repository path.---
description: "Cursor rules for designing a FastAPI HTTP contract with separate input and output models, accurate status codes, one error shape, bounded pagination and reviewed OpenAPI."
globs: "**/*"
alwaysApply: false
---
# FastAPI API Design Rules
Applies to: the public HTTP contract of a FastAPI service: paths, methods, request and response models, status codes, errors, pagination and the generated OpenAPI document.
Version baseline: checked against current FastAPI documentation with Pydantic v2. Read `pyproject.toml`/`requirements*.txt` for the installed FastAPI and Pydantic versions; Pydantic v1 projects use `.dict()` and `class Config` instead of `model_dump()` and `model_config`.
## Design the contract first
- Write down the resources, operations, models and error cases before implementing handlers. The OpenAPI document FastAPI generates (`/openapi.json`, `/docs`) is the contract: review it as part of the change.
- Resources are plural nouns (`/users`, `/users/{user_id}/orders`); the HTTP method carries the verb. Avoid paths like `/getUser`.
- Use one naming style for JSON fields across the API (the Python `snake_case` field names by default) and keep it stable.
## Request and response models
- Separate input and output models: `UserIn` (what clients may send) and `UserOut` (what the API returns). Server-assigned fields such as `id` and timestamps never appear in input models.
- Declare `response_model` (or a return annotation) on every endpoint so FastAPI filters the output and documents it. Never return ORM objects or dicts that may contain extra fields such as password hashes.
- Put validation in the models and parameters (`Field(min_length=...)`, `Query(ge=1, le=100)`), not in handler `if` statements. FastAPI then returns 422 with field-level details.
## Status codes
- `200` read/update, `201` create (with a `Location` header), `204` delete with no body.
- `404` missing resource, `409` conflict (duplicate unique field), `422` validation (automatic), `401`/`403` authentication/authorization.
- Never turn unexpected failures into `404`. Catch only the specific exception you can map; let anything else become a `500` and be logged.
## Errors
- Keep one error shape. FastAPI's default is `{"detail": ...}`; if you change it, register exception handlers once and use them everywhere.
- Document non-2xx responses with `responses={404: {"model": ErrorOut}}` so clients see them in OpenAPI.
- Raise domain exceptions in the data layer and map them to HTTP in the route or an exception handler.
## Pagination and filtering
- Collection endpoints are paginated from the start. Use `limit`/`offset` with bounds and return `total`, or cursor-based pagination for large or frequently changing tables.
- Filters and sorting are query parameters with explicit allowed values (`Literal[...]` or an `Enum`).
## Example
```python
from typing import Annotated
from fastapi import Depends, FastAPI, HTTPException, Query, Response, status
from pydantic import BaseModel, Field
app = FastAPI(title="Users API", version="1.0.0")
class UserIn(BaseModel):
name: str = Field(min_length=1, max_length=100)
email: str = Field(pattern=r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
class UserOut(UserIn):
id: int
class UserPage(BaseModel):
items: list[UserOut]
total: int
limit: int
offset: int
class ErrorOut(BaseModel):
detail: str
class UserNotFound(Exception):
pass
class UserRepo:
"""In-memory stand-in for the real data layer."""
def __init__(self) -> None:
self._rows: dict[int, UserOut] = {}
async def get(self, user_id: int) -> UserOut:
try:
return self._rows[user_id]
except KeyError:
raise UserNotFound(user_id) from None
async def page(self, limit: int, offset: int) -> tuple[list[UserOut], int]:
rows = sorted(self._rows.values(), key=lambda u: u.id)
return rows[offset : offset + limit], len(rows)
async def create(self, data: UserIn) -> UserOut:
user = UserOut(id=len(self._rows) + 1, **data.model_dump())
self._rows[user.id] = user
return user
repo = UserRepo()
def get_repo() -> UserRepo:
return repo
RepoDep = Annotated[UserRepo, Depends(get_repo)]
@app.get("/users", response_model=UserPage)
async def list_users(
repo: RepoDep,
limit: Annotated[int, Query(ge=1, le=100)] = 20,
offset: Annotated[int, Query(ge=0)] = 0,
) -> UserPage:
items, total = await repo.page(limit, offset)
return UserPage(items=items, total=total, limit=limit, offset=offset)
@app.get("/users/{user_id}", response_model=UserOut, responses={404: {"model": ErrorOut}})
async def get_user(user_id: int, repo: RepoDep) -> UserOut:
try:
return await repo.get(user_id)
except UserNotFound:
raise HTTPException(status_code=404, detail=f"User {user_id} not found") from None
@app.post("/users", response_model=UserOut, status_code=status.HTTP_201_CREATED)
async def create_user(data: UserIn, repo: RepoDep, response: Response) -> UserOut:
user = await repo.create(data)
response.headers["Location"] = f"/users/{user.id}"
return user
```
- An `async def` handler must only `await` coroutines. Awaiting a plain function's return value raises `TypeError`; combined with `except Exception`, that turns every request into a misleading error response.
- Blocking libraries (sync database drivers, `requests`) belong in a plain `def` handler or `run_in_threadpool`, not called directly in `async def`.
## Organization
- One `APIRouter` per resource module (`users`, `orders`, `auth`), included in the app with a prefix and tags.
- Inject the data layer with `Depends` so tests can replace it with `app.dependency_overrides`.
## Verify before finishing
Run these when they are available in the project:
- `pytest` with `TestClient` cases for each documented status code (200/201, 404, 422 for bad bodies and out-of-range query parameters)
- a check of `/openapi.json` for the new paths, models and error responses
- the project's type checker and linter
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
coding
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
A FastAPI + Pydantic v2 service has this rule attached while a developer asks Cursor to design and implement a users resource.
Add /users endpoints: list with pagination, get by id, and create. Clients send name and email; the server assigns the id. Document the 404 case.
Illustrative; not a recorded model run. UserIn without id and UserOut with id; GET /users with Query(ge=1, le=100) limit and offset returning items and total; GET /users/{user_id} that catches only the not-found domain error and raises 404, declared in responses={404: ...}; POST /users returning 201 with a Location header; repository injected with Depends; no broad except Exception; TestClient tests for 200, 201, 404 and 422.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/fastapi-api-design.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: "FastAPI API Design: Resources, Status Codes, Errors and Pagination project conventions"
globs: "**/*"
alwaysApply: false
---
# FastAPI API Design Rules
Applies to: the public HTTP contract of a FastAPI service: paths, methods, request and response models, status codes, errors, pagination and the generated OpenAPI document.
Version baseline: checked against current FastAPI documentation with Pydantic v2. Read `pyproject.toml`/`requirements*.txt` for the installed FastAPI and Pydantic versions; Pydantic v1 projects use `.dict()` and `class Config` instead of `model_dump()` and `model_config`.
## Design the contract first
- Write down the resources, operations, models and error cases before implementing handlers. The OpenAPI document FastAPI generates (`/openapi.json`, `/docs`) is the contract: review it as part of the change.
- Resources are plural nouns (`/users`, `/users/{user_id}/orders`); the HTTP method carries the verb. Avoid paths like `/getUser`.
- Use one naming style for JSON fields across the API (the Python `snake_case` field names by default) and keep it stable.
## Request and response models
- Separate input and output models: `UserIn` (what clients may send) and `UserOut` (what the API returns). Server-assigned fields such as `id` and timestamps never appear in input models.
- Declare `response_model` (or a return annotation) on every endpoint so FastAPI filters the output and documents it. Never return ORM objects or dicts that may contain extra fields such as password hashes.
- Put validation in the models and parameters (`Field(min_length=...)`, `Query(ge=1, le=100)`), not in handler `if` statements. FastAPI then returns 422 with field-level details.
## Status codes
- `200` read/update, `201` create (with a `Location` header), `204` delete with no body.
- `404` missing resource, `409` conflict (duplicate unique field), `422` validation (automatic), `401`/`403` authentication/authorization.
- Never turn unexpected failures into `404`. Catch only the specific exception you can map; let anything else become a `500` and be logged.
## Errors
- Keep one error shape. FastAPI's default is `{"detail": ...}`; if you change it, register exception handlers once and use them everywhere.
- Document non-2xx responses with `responses={404: {"model": ErrorOut}}` so clients see them in OpenAPI.
- Raise domain exceptions in the data layer and map them to HTTP in the route or an exception handler.
## Pagination and filtering
- Collection endpoints are paginated from the start. Use `limit`/`offset` with bounds and return `total`, or cursor-based pagination for large or frequently changing tables.
- Filters and sorting are query parameters with explicit allowed values (`Literal[...]` or an `Enum`).
## Example
```python
from typing import Annotated
from fastapi import Depends, FastAPI, HTTPException, Query, Response, status
from pydantic import BaseModel, Field
app = FastAPI(title="Users API", version="1.0.0")
class UserIn(BaseModel):
name: str = Field(min_length=1, max_length=100)
email: str = Field(pattern=r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
class UserOut(UserIn):
id: int
class UserPage(BaseModel):
items: list[UserOut]
total: int
limit: int
offset: int
class ErrorOut(BaseModel):
detail: str
class UserNotFound(Exception):
pass
class UserRepo:
"""In-memory stand-in for the real data layer."""
def __init__(self) -> None:
self._rows: dict[int, UserOut] = {}
async def get(self, user_id: int) -> UserOut:
try:
return self._rows[user_id]
except KeyError:
raise UserNotFound(user_id) from None
async def page(self, limit: int, offset: int) -> tuple[list[UserOut], int]:
rows = sorted(self._rows.values(), key=lambda u: u.id)
return rows[offset : offset + limit], len(rows)
async def create(self, data: UserIn) -> UserOut:
user = UserOut(id=len(self._rows) + 1, **data.model_dump())
self._rows[user.id] = user
return user
repo = UserRepo()
def get_repo() -> UserRepo:
return repo
RepoDep = Annotated[UserRepo, Depends(get_repo)]
@app.get("/users", response_model=UserPage)
async def list_users(
repo: RepoDep,
limit: Annotated[int, Query(ge=1, le=100)] = 20,
offset: Annotated[int, Query(ge=0)] = 0,
) -> UserPage:
items, total = await repo.page(limit, offset)
return UserPage(items=items, total=total, limit=limit, offset=offset)
@app.get("/users/{user_id}", response_model=UserOut, responses={404: {"model": ErrorOut}})
async def get_user(user_id: int, repo: RepoDep) -> UserOut:
try:
return await repo.get(user_id)
except UserNotFound:
raise HTTPException(status_code=404, detail=f"User {user_id} not found") from None
@app.post("/users", response_model=UserOut, status_code=status.HTTP_201_CREATED)
async def create_user(data: UserIn, repo: RepoDep, response: Response) -> UserOut:
user = await repo.create(data)
response.headers["Location"] = f"/users/{user.id}"
return user
```
- An `async def` handler must only `await` coroutines. Awaiting a plain function's return value raises `TypeError`; combined with `except Exception`, that turns every request into a misleading error response.
- Blocking libraries (sync database drivers, `requests`) belong in a plain `def` handler or `run_in_threadpool`, not called directly in `async def`.
## Organization
- One `APIRouter` per resource module (`users`, `orders`, `auth`), included in the app with a prefix and tags.
- Inject the data layer with `Depends` so tests can replace it with `app.dependency_overrides`.
## Verify before finishing
Run these when they are available in the project:
- `pytest` with `TestClient` cases for each documented status code (200/201, 404, 422 for bad bodies and out-of-range query parameters)
- a check of `/openapi.json` for the new paths, models and error responses
- the project's type checker and linter
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.