Cursor rule for layered FastAPI backends with routers, services and repositories, typed settings, one domain-error mapping and limits on BackgroundTasks.
.cursor/rules/python-backend-development.mdc. Downloaded files need to be placed in that repository path.---
description: "Cursor rule for layered FastAPI backends with routers, services and repositories, typed settings, one domain-error mapping and limits on BackgroundTasks."
globs: "**/*"
alwaysApply: false
---
# Python Backend Development (FastAPI service layering)
Applies to: Python HTTP services built with FastAPI, structured as routes, services and repositories.
Version baseline: checked against FastAPI and Pydantic v2 documentation, and against Python 3.15. The examples use 3.10+ syntax (`X | None`). Read `requires-python` and the pinned FastAPI/Pydantic versions in `pyproject.toml`. If they differ, follow the project's versions.
## Code style
- Type-hint public function signatures and Pydantic models. Use built-in generics (`list[str]`) and `X | None`.
- Follow PEP 8 and PEP 257 docstrings for public modules, classes and functions. Use the project's formatter and linter (for example ruff or black) instead of hand-formatting.
- Use `async def` for route handlers only when the I/O inside them is async. A plain `def` handler that does sync I/O is fine, because FastAPI runs it in a threadpool. A sync DB call inside `async def` blocks the event loop.
## Layering
```
src/app/
├── api/ # routers: HTTP parsing, status codes, response models only
├── core/ # settings, logging, security helpers
├── schemas/ # Pydantic request/response models
├── services/ # business rules; no FastAPI or HTTP types
├── repositories/ # data access (SQL, ORM, external APIs)
└── main.py # app factory, router registration, exception handlers
```
- Routers call services. Services call repositories. Do not import FastAPI `Request`, `HTTPException` or `status` inside `services/` or `repositories/`. Services raise domain exceptions instead.
- Inject dependencies with `Depends` (or `Annotated[..., Depends(...)]`) so tests can replace them with `app.dependency_overrides`.
- Keep request/response schemas separate from ORM models. Never return ORM objects that contain secrets, such as password hashes, without a `response_model` that filters them.
## Configuration
- Read configuration from environment variables once, at startup, into a typed settings object. `pydantic-settings` is a separate package; use it if the project already does. Never hard-code secrets or commit `.env` files.
## Errors
Define a small set of domain exceptions and map them to HTTP responses in one place:
```python
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
class DomainError(Exception):
status_code = 400
code = "bad_request"
def __init__(self, message: str) -> None:
super().__init__(message)
self.message = message
class NotFoundError(DomainError):
status_code = 404
code = "not_found"
def register_error_handlers(app: FastAPI) -> None:
@app.exception_handler(DomainError)
async def handle_domain_error(request: Request, exc: DomainError) -> JSONResponse:
return JSONResponse(
status_code=exc.status_code,
content={"error": {"code": exc.code, "message": exc.message}},
)
```
- Return one consistent error shape. Let unexpected exceptions reach the default 500 handler and your logging or monitoring. Do not echo stack traces or internal messages to clients.
- Use correct status codes: 201 with the created resource for POST, 204 with no body for DELETE, 404 for missing resources, 409 for conflicts, 422 for validation errors (FastAPI's default).
## Background work
- `BackgroundTasks` runs in the same process after the response is sent. It is lost if the process restarts, and it gets no retries. Use it only for short, best-effort work such as sending a notification email.
- For heavy, slow or must-not-lose work, enqueue a job in the project's queue (for example Celery, RQ, arq or a cloud queue) and return 202.
## Verify before finishing
- Add or update tests that use `fastapi.testclient.TestClient` with `app.dependency_overrides` for repositories. Cover the happy path, each mapped domain error and validation failures (422).
- Run the project's test, lint and type-check commands when available (for example `pytest`, `ruff check`, `mypy`).
- Check that no file in `services/` or `repositories/` imports from `fastapi`.
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 team keeps a FastAPI service in src/app with api/, services/ and repositories/ folders and wants Cursor to add endpoints without leaking HTTP concerns into business code.
Add GET /users/{user_id} to src/app/api/users.py. The repository is injected by get_user_repo(). Return 404 using our existing NotFoundError and never expose password_hash. After a successful read, record an audit event, which may be best-effort.Illustrative; not a recorded model run. A router function with a response_model that omits password_hash and calls a service function. The service raises NotFoundError, not HTTPException, and the shared exception handler turns it into {"error": {"code": "not_found", ...}} with status 404. The audit event is added with BackgroundTasks, with a note that it is best-effort. A TestClient test overrides get_user_repo and asserts the 200, 404 and 422 cases.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-backend-development.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 Backend Development: FastAPI Service Layering and Error Handling project conventions"
globs: "**/*"
alwaysApply: false
---
# Python Backend Development (FastAPI service layering)
Applies to: Python HTTP services built with FastAPI, structured as routes, services and repositories.
Version baseline: checked against FastAPI and Pydantic v2 documentation, and against Python 3.15. The examples use 3.10+ syntax (`X | None`). Read `requires-python` and the pinned FastAPI/Pydantic versions in `pyproject.toml`. If they differ, follow the project's versions.
## Code style
- Type-hint public function signatures and Pydantic models. Use built-in generics (`list[str]`) and `X | None`.
- Follow PEP 8 and PEP 257 docstrings for public modules, classes and functions. Use the project's formatter and linter (for example ruff or black) instead of hand-formatting.
- Use `async def` for route handlers only when the I/O inside them is async. A plain `def` handler that does sync I/O is fine, because FastAPI runs it in a threadpool. A sync DB call inside `async def` blocks the event loop.
## Layering
```
src/app/
├── api/ # routers: HTTP parsing, status codes, response models only
├── core/ # settings, logging, security helpers
├── schemas/ # Pydantic request/response models
├── services/ # business rules; no FastAPI or HTTP types
├── repositories/ # data access (SQL, ORM, external APIs)
└── main.py # app factory, router registration, exception handlers
```
- Routers call services. Services call repositories. Do not import FastAPI `Request`, `HTTPException` or `status` inside `services/` or `repositories/`. Services raise domain exceptions instead.
- Inject dependencies with `Depends` (or `Annotated[..., Depends(...)]`) so tests can replace them with `app.dependency_overrides`.
- Keep request/response schemas separate from ORM models. Never return ORM objects that contain secrets, such as password hashes, without a `response_model` that filters them.
## Configuration
- Read configuration from environment variables once, at startup, into a typed settings object. `pydantic-settings` is a separate package; use it if the project already does. Never hard-code secrets or commit `.env` files.
## Errors
Define a small set of domain exceptions and map them to HTTP responses in one place:
```python
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
class DomainError(Exception):
status_code = 400
code = "bad_request"
def __init__(self, message: str) -> None:
super().__init__(message)
self.message = message
class NotFoundError(DomainError):
status_code = 404
code = "not_found"
def register_error_handlers(app: FastAPI) -> None:
@app.exception_handler(DomainError)
async def handle_domain_error(request: Request, exc: DomainError) -> JSONResponse:
return JSONResponse(
status_code=exc.status_code,
content={"error": {"code": exc.code, "message": exc.message}},
)
```
- Return one consistent error shape. Let unexpected exceptions reach the default 500 handler and your logging or monitoring. Do not echo stack traces or internal messages to clients.
- Use correct status codes: 201 with the created resource for POST, 204 with no body for DELETE, 404 for missing resources, 409 for conflicts, 422 for validation errors (FastAPI's default).
## Background work
- `BackgroundTasks` runs in the same process after the response is sent. It is lost if the process restarts, and it gets no retries. Use it only for short, best-effort work such as sending a notification email.
- For heavy, slow or must-not-lose work, enqueue a job in the project's queue (for example Celery, RQ, arq or a cloud queue) and return 202.
## Verify before finishing
- Add or update tests that use `fastapi.testclient.TestClient` with `app.dependency_overrides` for repositories. Cover the happy path, each mapped domain error and validation failures (422).
- Run the project's test, lint and type-check commands when available (for example `pytest`, `ruff check`, `mypy`).
- Check that no file in `services/` or `repositories/` imports from `fastapi`.
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.