Skip to content

FastAPI + SQLAlchemy + pytest rules for AI coding agents

Full stack: Python + FastAPI + SQLAlchemy 2 + Alembic + pytest + Docker

Ready-to-commit rules for Python + FastAPI + SQLAlchemy 2 + Alembic + pytest + Docker in every major format: AGENTS.md (Codex, Cursor, Copilot), CLAUDE.md (Claude Code), Cursor .mdc project rules, legacy .cursorrules, Copilot instructions, Windsurf rules and GEMINI.md. A production-style Python API: FastAPI, SQLAlchemy 2 and Alembic, tested with pytest.

Last reviewed 2026-10-21 · Customise in the generator · Raw: AGENTS.md, CLAUDE.md

The mistake agents make most on this stack

Agents mix legacy `session.query()` with 2.0 style and block the event loop with sync calls in `async def`.

Generated files

AGENTS.md
# AGENTS.md - this project

Instructions for AI coding agents working in this repository.

## Project

A Python + FastAPI + SQLAlchemy 2 + Alembic + pytest + Docker project.

Stack: Python + FastAPI, SQLAlchemy 2 + Alembic, pytest, Docker.

## Commands

- Install deps: `uv sync`
- Dev server: `uv run fastapi dev`
- Lint and format: `uv run ruff check . && uv run ruff format .`
- Tests: `uv run pytest`
- New migration: `uv run alembic revision --autogenerate -m "<change>"`
- Apply migrations: `uv run alembic upgrade head`
- Tests: `uv run pytest -q`
- Local services: `docker compose up -d`

## Project structure

- `app/main.py` creates the app; one `APIRouter` per domain in `app/routers/`.
- Pydantic schemas in `app/schemas/`, business logic in `app/services/`.

## How to work in this repo

- Read the relevant files before editing. Follow the patterns already in the codebase over these generic rules.
- Make the smallest change that solves the task. Do not refactor or reformat unrelated code.
- Before saying a task is done, run the type-check, lint and tests listed under Commands and fix what you broke.
- If requirements are ambiguous, ask one clear question instead of guessing.
- Never commit secrets, API keys or `.env` files. Use env vars and keep `.env.example` up to date.
- Do not add a new dependency when the standard library or an existing dependency already covers it.
- Ask before adding, removing or upgrading any dependency.
- Ask before changing database schemas, auth, payments or CI configuration.
- Never delete files, drop data or run destructive commands (`rm -rf`, `git push --force`, `DROP TABLE`) without explicit approval.
- Keep each change under ~200 changed lines where possible; split larger work into steps.

## Python + FastAPI

- Type-hint every function. Use `Annotated[..., Depends(...)]` for dependencies.
- Request and response bodies are Pydantic v2 models; set `response_model` so output is filtered.
- Use `async def` only when the endpoint awaits async I/O. Blocking libraries go in plain `def` endpoints.
- Inject DB sessions, settings and the current user with dependencies, not globals.
- Load settings with `pydantic-settings` from env vars.
- Raise `HTTPException` with a clear `detail` for expected errors.
- Manage dependencies with `uv add <pkg>`; do not hand-edit lock files.

## SQLAlchemy 2 + Alembic

- Use SQLAlchemy 2.0 style: `DeclarativeBase`, `Mapped[...]`, `mapped_column()`, and `select()` statements. No legacy `session.query()`.
- Every schema change gets an Alembic migration; review autogenerated migrations before applying.
- Scope one session per request (via a dependency) and never share sessions across threads.
- Load relationships deliberately with `selectinload` / `joinedload` to avoid N+1 queries.

## pytest

- Tests live in `tests/` named `test_*.py`. Use plain `assert`.
- Share setup with fixtures in `conftest.py`; use `@pytest.mark.parametrize` for input tables.
- Mock external services (HTTP, LLM APIs, payment providers); tests must not hit the network.
- Every bug fix adds a regression test.

## Docker

- Use multi-stage builds and slim, pinned base images.
- Run the app as a non-root user in the final image.
- Keep a `.dockerignore` that excludes `.git`, `node_modules`, `.env` and build output.
- Never bake secrets into images; pass them at runtime.

## Reference docs

- [FastAPI docs](https://fastapi.tiangolo.com)
- [SQLAlchemy docs](https://docs.sqlalchemy.org/en/20/)
- [pytest docs](https://docs.pytest.org)
- [Dockerfile best practices](https://docs.docker.com/build/building/best-practices/)

Commands your agent should run

TaskCommand
Install depsuv sync
Dev serveruv run fastapi dev
Lint and formatuv run ruff check . && uv run ruff format .
Testsuv run pytest
New migrationuv run alembic revision --autogenerate -m "<change>"
Apply migrationsuv run alembic upgrade head
Testsuv run pytest -q
Local servicesdocker compose up -d

What the rules cover

Python + FastAPI

FastAPI service with Pydantic v2 and uv. Scoped to **/*.py in Cursor, Copilot and Windsurf.

  • Type-hint every function. Use Annotated[..., Depends(...)] for dependencies.
  • Request and response bodies are Pydantic v2 models; set response_model so output is filtered.
  • Use async def only when the endpoint awaits async I/O. Blocking libraries go in plain def endpoints.
  • Inject DB sessions, settings and the current user with dependencies, not globals.
  • Load settings with pydantic-settings from env vars.
  • Raise HTTPException with a clear detail for expected errors.
  • Manage dependencies with uv add <pkg>; do not hand-edit lock files.

Source docs: FastAPI docs

SQLAlchemy 2 + Alembic

SQLAlchemy 2.0 ORM with Alembic migrations. Scoped to **/models/**/*.py, alembic/** in Cursor, Copilot and Windsurf.

  • Use SQLAlchemy 2.0 style: DeclarativeBase, Mapped[...], mapped_column(), and select() statements. No legacy session.query().
  • Every schema change gets an Alembic migration; review autogenerated migrations before applying.
  • Scope one session per request (via a dependency) and never share sessions across threads.
  • Load relationships deliberately with selectinload / joinedload to avoid N+1 queries.

Source docs: SQLAlchemy docs

pytest

Python tests with pytest. Scoped to tests/**/*.py, **/test_*.py in Cursor, Copilot and Windsurf.

  • Tests live in tests/ named test_*.py. Use plain assert.
  • Share setup with fixtures in conftest.py; use @pytest.mark.parametrize for input tables.
  • Mock external services (HTTP, LLM APIs, payment providers); tests must not hit the network.
  • Every bug fix adds a regression test.

Source docs: pytest docs

Docker

Containerised builds and local services with Docker. Scoped to Dockerfile, **/Dockerfile, compose.yaml, docker-compose.yml, .dockerignore in Cursor, Copilot and Windsurf.

  • Use multi-stage builds and slim, pinned base images.
  • Run the app as a non-root user in the final image.
  • Keep a .dockerignore that excludes .git, node_modules, .env and build output.
  • Never bake secrets into images; pass them at runtime.

Source docs: Dockerfile best practices

How to install

  1. Copy AGENTS.md to your repo root. That covers Codex, Cursor, GitHub Copilot and most other agents.
  2. Using Claude Code? Add a CLAUDE.md with the single line @AGENTS.md, or use the standalone CLAUDE.md tab above.
  3. Want rules that only load for certain files in Cursor? Add the .cursor/rules/*.mdc files.
  4. Commit the files so your whole team (and every agent) shares them.

FAQ

Where do I put the AGENTS.md for Python + FastAPI + SQLAlchemy 2 + Alembic + pytest + Docker?

Save it as AGENTS.md in the root of your repository, next to your main config file. Codex, Cursor and GitHub Copilot pick it up automatically. For Claude Code, add a CLAUDE.md containing @AGENTS.md (or use the standalone CLAUDE.md on this page).

What is the most common mistake AI agents make with Python + FastAPI?

Agents mix legacy session.query() with 2.0 style and block the event loop with sync calls in async def.

Which commands should the agent run to check its work?

For this stack: uv sync, uv run fastapi dev, uv run ruff check . && uv run ruff format ., uv run pytest. They are listed in the generated files so the agent runs them before finishing a task.

Do these Python + FastAPI + SQLAlchemy 2 + Alembic + pytest + Docker rules work with Cursor and Claude Code?

Yes. This page includes the same rules as AGENTS.md, CLAUDE.md, Cursor .mdc project rules, a legacy .cursorrules file, GitHub Copilot instructions, Windsurf rules and GEMINI.md.

Can I customise these rules?

Yes. Open this stack in the generator to add or remove libraries, set your project name and package manager, switch beginner explanations on, and download everything as a zip.

Related stacks