Home › Python / FastAPI › Python FastAPI rules

Python FastAPI rules

Cursor rules for FastAPI services with Pydantic v2, SQLAlchemy 2.0, async, and pytest.

CursorPython / FastAPI

How to use

Save this as .cursor/rules/fastapi.mdc in your repository root, commit it, and your agent will pick it up automatically. Edit the commands to match your project.

.cursor/rules/fastapi.mdcDownload  
---
description: FastAPI service conventions
globs: ["**/*.py"]
alwaysApply: true
---

# FastAPI

- Python 3.12+, full type hints on every function. Run `ruff check --fix` and `mypy --strict`.
- Layout: `app/api/routes/*` (thin routers) → `app/services/*` (business logic) → `app/repositories/*` (DB).
- Request and response bodies are Pydantic v2 models in `app/schemas/`. Never return ORM objects directly; set `response_model`.
- Use `async def` endpoints with SQLAlchemy 2.0 `AsyncSession` injected via `Depends(get_session)`.
- Settings via `pydantic-settings` `BaseSettings`; no `os.getenv` scattered in code.
- Raise `HTTPException` only in routers; services raise domain exceptions mapped by an exception handler.
- Migrations with Alembic: `alembic revision --autogenerate -m "..."`, then review the diff.
- Tests: pytest + `httpx.AsyncClient` with `ASGITransport`; each new endpoint needs a happy-path and an error-path test.
- Log with `structlog`/`logging`, never `print`.

Related rules

Astro content site rules

Cursor rules for Astro 5 sites with content collections, islands, and zero-JS-by-default pages.

CursorAstro

Chrome extension (Manifest V3) rules

Cursor rules for building Manifest V3 browser extensions with TypeScript and minimal permissions.

CursorChrome extensions

Universal vibe-coding guardrails

Always-on Cursor rules that keep any AI agent careful: plan first, small diffs, verify, never fake it.

CursorAny stack

Next.js App Router (TypeScript) rules

Cursor project rules for Next.js 15 App Router apps with TypeScript, Server Components, and Tailwind.

CursorNext.js

Get new rules weekly

One email a week: fresh rule files, agent tips, and what's changing in Cursor, Claude Code and Copilot. Free, unsubscribe anytime.

Opens the Rulestack Newsletter on beehiiv in a new tab. Or subscribe directly on beehiiv.