Agent instructionsScan: pass
Python uv + FastAPI CLAUDE.md
CLAUDE.md for a Python 3.12+ FastAPI service managed with uv, tested with pytest, linted with ruff, type-checked with mypy or pyright.
Add a trust badge to your README
[](https://waxmark.app/items/python-uv-fastapi-claude-md/scan)
# {{PROJECT_NAME}}
FastAPI service. Python {{PYTHON_VERSION}} (pinned in `.python-version`), dependencies managed by **uv**, Pydantic v2, SQLAlchemy 2.x async. Source package is `src/{{PACKAGE_NAME}}/`.
## Commands
| Task | Command |
|------|---------|
| Install / sync env | `uv sync` (creates `.venv/` and installs the locked set) |
| Run server | `uv run fastapi dev src/{{PACKAGE_NAME}}/main.py` |
| Test | `uv run pytest` (one test: `uv run pytest tests/test_users.py::test_create -x`) |
| Lint | `uv run ruff check .` (autofix: `uv run ruff check --fix .`) |
| Format | `uv run ruff format .` (check only: `uv run ruff format --check .`) |
| Types | `uv run {{TYPE_CHECKER}} src` |
| Add dependency | `uv add <pkg>`; dev-only: `uv add --dev <pkg>` |
| Migrations | `uv run alembic revision --autogenerate -m "<change>"` then `uv run alembic upgrade head` |
Definition of done: `uv run ruff check .`, `uv run ruff format --check .`, `uv run {{TYPE_CHECKER}} src`, and `uv run pytest` all exit 0. Paste the pytest summary line in your report.
## Environment rules
- Never run `pip install`, `python -m venv`, `poetry`, or `conda`. uv owns the environment. If a package is missing, `uv add` it so `pyproject.toml` and `uv.lock` change together.
- Always invoke tools through `uv run`; do not rely on an activated shell.
- Commit `uv.lock`. Never hand-edit it; run `uv lock` after changing `pyproject.toml` manually.
- Configuration for ruff, pytest, and the type checker lives in `pyproject.toml`. Do not add `setup.cfg`, `tox.ini`, or `.flake8`.
## Code conventions
- Type hints on every function signature, including `-> None`. Use `X | None`, not `Optional[X]`. Use built-in generics (`list[str]`, `dict[str, int]`).
- Imports: absolute from `{{PACKAGE_NAME}}`. No relative imports beyond one dot.
- Logging via `structlog.get_logger()`; no `print()` outside `scripts/`.
- Raise `HTTPException` only in the router layer. Service-layer code raises domain exceptions from `{{PACKAGE_NAME}}.errors`; `main.py` registers exception handlers that map them to status codes.
## FastAPI patterns
- Routers in `src/{{PACKAGE_NAME}}/api/<resource>.py`, each exporting `router = APIRouter(prefix="/<resource>", tags=["<resource>"])`. Register in `main.py`.
- Dependencies use `Annotated`: `db: Annotated[AsyncSession, Depends(get_session)]`. Define shared aliases in `api/deps.py`.
- Startup and shutdown go in the `lifespan` async context manager passed to `FastAPI(lifespan=...)`. Do not use `@app.on_event`.
- Every endpoint declares `response_model` (or a return annotation) with a Pydantic schema. Never return ORM objects directly.
## Async rules
- All route handlers and DB access are `async def`. Blocking calls (file IO, `requests`, CPU-heavy work) go through `await asyncio.to_thread(...)` or `fastapi.concurrency.run_in_threadpool`.
- Use `httpx.AsyncClient` for outbound HTTP, created once in `lifespan` and stored on `app.state`.
- Do not create a new engine or client per request.
## Pydantic v2
- Schemas in `src/{{PACKAGE_NAME}}/schemas/`. Use `model_config = ConfigDict(from_attributes=True)` for schemas built from ORM rows.
- Use `model_validate`, `model_dump`, `model_dump_json`. The v1 names (`parse_obj`, `.dict()`, `.json()`, `@validator`, `class Config`) are forbidden.
- Validators: `@field_validator("field")` and `@model_validator(mode="after")`.
- Settings come from one `pydantic_settings.BaseSettings` subclass in `config.py`, loaded once. Do not read `os.environ` elsewhere.
## Testing
- `pytest` with `pytest-asyncio` in `asyncio_mode = "auto"`; write `async def test_...` with no decorator.
- Hit the app through `httpx.AsyncClient(transport=ASGITransport(app=app), base_url="http://test")`. Do not start uvicorn in tests.
- Database tests use the `db_session` fixture in `tests/conftest.py`: fresh schema per session, each test inside a rolled-back transaction.
- Factories in `tests/factories.py`. No raw dict fixtures for models.
## Do not
- Do not add `# type: ignore` without a specific error code and a trailing reason.
- Do not widen `ruff` ignores in `pyproject.toml` to silence a finding; fix the code.
- Do not edit files under `alembic/versions/` after they are committed; add a new revision.