Cursor rule with a FastAPI endpoint checklist covering Pydantic models, Annotated dependencies, lifespan, explicit CORS, error handlers and TestClient tests.
.cursor/rules/python-fastapi-best-practices.mdc. Downloaded files need to be placed in that repository path.---
description: "Cursor rule with a FastAPI endpoint checklist covering Pydantic models, Annotated dependencies, lifespan, explicit CORS, error handlers and TestClient tests."
globs: "**/*"
alwaysApply: false
---
# FastAPI Best Practices Checklist
Applies to: any FastAPI application. Use this as the review checklist for new or changed endpoints.
Version baseline: checked against the current FastAPI and Pydantic v2 documentation. Examples use Python 3.10+ syntax. Read the pinned `fastapi` and `pydantic` versions and `requires-python` in the project, and follow them if they differ.
## 1. Validate input and output with Pydantic models
- Request bodies are Pydantic models. Add constraints with `Field(...)` (`min_length`, `gt`, `pattern`) instead of manual `if` checks.
- Set `response_model` (or a return type annotation) on every endpoint so responses are filtered and documented. Never return ORM objects or dicts that contain secrets without one.
## 2. Use dependency injection with Annotated
```python
from typing import Annotated
from fastapi import Depends, FastAPI, Header, HTTPException
async def get_current_user(authorization: Annotated[str | None, Header()] = None) -> dict:
if authorization != "Bearer test-token": # replace with real verification
raise HTTPException(status_code=401, detail="Not authenticated")
return {"id": 1}
CurrentUser = Annotated[dict, Depends(get_current_user)]
app = FastAPI()
@app.get("/me")
async def read_me(user: CurrentUser) -> dict:
return user
```
- Reuse `Annotated` aliases (`CurrentUser`, `DbSession`) instead of repeating `Depends(...)`.
- Put cross-cutting checks (auth, tenant, feature flags) in dependencies, and override them in tests with `app.dependency_overrides`.
## 3. Manage startup and shutdown with lifespan
```python
from contextlib import asynccontextmanager
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.http = make_http_client() # project resource
yield
await app.state.http.aclose()
app = FastAPI(lifespan=lifespan)
```
`@app.on_event("startup")` / `("shutdown")` are deprecated, and they are not called when `lifespan` is set.
## 4. Use BackgroundTasks only for small, best-effort work
`BackgroundTasks` runs in the same process after the response is sent, with no retry or persistence. Use a job queue for slow, heavy or must-not-lose work, and return `202 Accepted` with a job id.
## 5. Configure CORS explicitly
```python
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["https://app.example.com"], # from settings, per environment
allow_credentials=True,
allow_methods=["GET", "POST", "PATCH", "DELETE"],
allow_headers=["Authorization", "Content-Type"],
)
```
Do not combine `allow_origins=["*"]` with `allow_credentials=True`. List the real front-end origins. CORS is a browser policy, not authentication, so still protect every endpoint.
## 6. Handle errors consistently
- Raise `HTTPException` with an accurate status (`404`, `409`, `403`) in routes. Raise domain exceptions in service code, and map them once with `@app.exception_handler(...)`.
- Keep FastAPI's 422 validation responses unless the API contract requires another shape. Then override `RequestValidationError` once, globally.
- Never return stack traces or raw exception messages to clients.
## 7. Path operations and OpenAPI
- Use the matching decorator (`@app.get`, `.post`, `.put`, `.patch`, `.delete`) and set `status_code` explicitly for non-200 success (201 create, 204 delete).
- Group endpoints with `APIRouter(prefix=..., tags=[...])`, and add `summary` and `responses={404: {...}}` so the generated `/docs` and `/openapi.json` describe the contract.
- Disable or protect `/docs` in production only if the project's policy requires it (`FastAPI(docs_url=None)`).
## 8. Test with TestClient
```python
from fastapi.testclient import TestClient
def test_me_requires_auth():
with TestClient(app) as client: # the with-block runs lifespan startup and shutdown
assert client.get("/me").status_code == 401
ok = client.get("/me", headers={"Authorization": "Bearer test-token"})
assert ok.json() == {"id": 1}
```
Use `httpx.AsyncClient` with `ASGITransport` when the test itself must be async.
## Verify before finishing
- Run the project's tests (`pytest`), and open `/openapi.json` to confirm the status codes and models of the changed endpoints.
- Check that every new endpoint has a response model, an auth dependency (or a documented reason it is public), and a test for its main error case.
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 developer asks Cursor to add or review an authenticated FastAPI endpoint, and wants the change checked against a short, consistent checklist.
Review and fix main.py: it uses @app.on_event('startup') to create an httpx client, CORS allow_origins=['*'] with allow_credentials=True, and GET /me returns the ORM user including password_hash. Front-end origin is https://app.example.com.Illustrative; not a recorded model run. A diff that moves the httpx client into a lifespan context manager (created before yield, closed after) and replaces '*' with the explicit origin, methods and headers from settings. It adds a response_model or return type that excludes password_hash, an Annotated CurrentUser dependency, and TestClient tests (inside a with-block) for 401 without a token, 200 with one, and the CORS preflight from the allowed origin.
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-best-practices.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 Best Practices: An 8-Point Endpoint Review Checklist project conventions"
globs: "**/*"
alwaysApply: false
---
# FastAPI Best Practices Checklist
Applies to: any FastAPI application. Use this as the review checklist for new or changed endpoints.
Version baseline: checked against the current FastAPI and Pydantic v2 documentation. Examples use Python 3.10+ syntax. Read the pinned `fastapi` and `pydantic` versions and `requires-python` in the project, and follow them if they differ.
## 1. Validate input and output with Pydantic models
- Request bodies are Pydantic models. Add constraints with `Field(...)` (`min_length`, `gt`, `pattern`) instead of manual `if` checks.
- Set `response_model` (or a return type annotation) on every endpoint so responses are filtered and documented. Never return ORM objects or dicts that contain secrets without one.
## 2. Use dependency injection with Annotated
```python
from typing import Annotated
from fastapi import Depends, FastAPI, Header, HTTPException
async def get_current_user(authorization: Annotated[str | None, Header()] = None) -> dict:
if authorization != "Bearer test-token": # replace with real verification
raise HTTPException(status_code=401, detail="Not authenticated")
return {"id": 1}
CurrentUser = Annotated[dict, Depends(get_current_user)]
app = FastAPI()
@app.get("/me")
async def read_me(user: CurrentUser) -> dict:
return user
```
- Reuse `Annotated` aliases (`CurrentUser`, `DbSession`) instead of repeating `Depends(...)`.
- Put cross-cutting checks (auth, tenant, feature flags) in dependencies, and override them in tests with `app.dependency_overrides`.
## 3. Manage startup and shutdown with lifespan
```python
from contextlib import asynccontextmanager
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.http = make_http_client() # project resource
yield
await app.state.http.aclose()
app = FastAPI(lifespan=lifespan)
```
`@app.on_event("startup")` / `("shutdown")` are deprecated, and they are not called when `lifespan` is set.
## 4. Use BackgroundTasks only for small, best-effort work
`BackgroundTasks` runs in the same process after the response is sent, with no retry or persistence. Use a job queue for slow, heavy or must-not-lose work, and return `202 Accepted` with a job id.
## 5. Configure CORS explicitly
```python
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["https://app.example.com"], # from settings, per environment
allow_credentials=True,
allow_methods=["GET", "POST", "PATCH", "DELETE"],
allow_headers=["Authorization", "Content-Type"],
)
```
Do not combine `allow_origins=["*"]` with `allow_credentials=True`. List the real front-end origins. CORS is a browser policy, not authentication, so still protect every endpoint.
## 6. Handle errors consistently
- Raise `HTTPException` with an accurate status (`404`, `409`, `403`) in routes. Raise domain exceptions in service code, and map them once with `@app.exception_handler(...)`.
- Keep FastAPI's 422 validation responses unless the API contract requires another shape. Then override `RequestValidationError` once, globally.
- Never return stack traces or raw exception messages to clients.
## 7. Path operations and OpenAPI
- Use the matching decorator (`@app.get`, `.post`, `.put`, `.patch`, `.delete`) and set `status_code` explicitly for non-200 success (201 create, 204 delete).
- Group endpoints with `APIRouter(prefix=..., tags=[...])`, and add `summary` and `responses={404: {...}}` so the generated `/docs` and `/openapi.json` describe the contract.
- Disable or protect `/docs` in production only if the project's policy requires it (`FastAPI(docs_url=None)`).
## 8. Test with TestClient
```python
from fastapi.testclient import TestClient
def test_me_requires_auth():
with TestClient(app) as client: # the with-block runs lifespan startup and shutdown
assert client.get("/me").status_code == 401
ok = client.get("/me", headers={"Authorization": "Bearer test-token"})
assert ok.json() == {"id": 1}
```
Use `httpx.AsyncClient` with `ASGITransport` when the test itself must be async.
## Verify before finishing
- Run the project's tests (`pytest`), and open `/openapi.json` to confirm the status codes and models of the changed endpoints.
- Check that every new endpoint has a response model, an auth dependency (or a documented reason it is public), and a test for its main error case.
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.