fastapi-best-practices
Installation
SKILL.md
In this repository
- Scope: FastAPI app lives in
backend/. Python also inservices/; same style applies. After edits runmake formatandmake lintfrom repo root. - Rules:
.cursor/rules/fastapi-python-best-practices.md,.cursor/rules/fastapi-patterns.md,.cursor/rules/standards.md,.cursor/rules/project.md. - Full context:
.cursor/skills/README.md.
FastAPI best practices (team standards)
Standards derived from this project’s implementation. Follow these so the codebase stays consistent and maintainable.
1. Project structure and layers
- Endpoints (controllers):
backend/app/api/v1/endpoints/— one file per domain (e.g.data.py,database.py,metrics.py). Only HTTP concerns: parse request, call service/repo viaDepends, return response or raiseHTTPException. Use command service for write operations (POST/PUT/PATCH/DELETE) and query service for read operations (GET). See.cursor/rules/cqrs.md. - Business logic:
backend/app/services/— use command services for writes and query services for reads (CQRS). Services receive repositories via constructor; useAsyncSessionfor DB when in the API path. No raw request/response objects. - Data access:
backend/app/repositories/— use write repositories (create/update/delete) and read repositories (get/list) per domain. Repositories receiveAsyncSession; perform queries and commits. No business rules. - Shared dependencies:
backend/app/api/v1/deps.py— defineget_*functions that return service or repository instances (injectingget_async_session). Use these in route handlers viaDepends(...). - Models:
backend/app/models/database.py(SQLModel table models),backend/app/models/schemas.py(Pydantic request/response). DB name is fastapi_db.