Skip to content

project rulesBackend and APIspythonfastapi

Python FastAPI Rules

Project rules for FastAPI services: typed Pydantic models, dependency injection, async-safe database access and consistent error responses.

npx workspacetemplates add python-fastapi-rules --tool claude-code

Writes 1 file to your project root

CLAUDE.mdadd to your file21 lines · 1.3 KBFile
# Project rules: Python FastAPI

## Structure
- Layers: `routers/` (HTTP only), `services/` (business rules), `repositories/` (database), `schemas/` (Pydantic), `models/` (ORM). A router never talks to the database directly.
- One router per resource, with `APIRouter(prefix=..., tags=[...])`. Set `response_model`, `status_code` and error responses on every route.

## Typing and validation
- Python 3.11+, full type hints, `mypy --strict` or pyright clean.
- Separate input and output schemas (`UserCreate`, `UserRead`). Never return an ORM object or a password hash directly. Use `model_config = ConfigDict(from_attributes=True)`.

## Dependencies and async
- Use `Depends` for the database session, current user and settings. Settings come from `pydantic-settings`, never from `os.environ` inside routes.
- Use `async def` only with async drivers. Blocking code (requests, sync ORM, file I/O) goes in `def` routes or `run_in_threadpool`.
- Commit in the service layer once per request; roll back on error.

## Errors
- Raise `HTTPException` or a domain error mapped by an exception handler to `{"error": {"code", "message"}}`. Never expose stack traces.

## Tests and tooling
- pytest with `httpx.AsyncClient`, override dependencies instead of patching. Migrations through Alembic only.
- Before finishing run `ruff check`, `ruff format`, mypy and `pytest`.

What it does

FastAPI makes it easy to write an endpoint and just as easy to write one that blocks the event loop or leaks database rows. These rules fix the structure so every new route looks like the last one.

They name the layers, say where validation lives and spell out the testing and tooling the agent must run before it calls a change finished.

Example

you › Add a DELETE endpoint for projects owned by the current user

agent › The agent adds the route to routers/projects.py, a delete method in the service that checks ownership, a repository call, a 404 for foreign projects and an async test with an overridden current-user dependency.

Questions

Does it assume SQLAlchemy?
It assumes a repository layer and works with SQLAlchemy or SQLModel. The async advice applies to either one.
Why separate read and create schemas?
It stops fields such as ids and password hashes from leaking or being set by the client.
  • ASP.NET Core Web API Rules

    Project rulesdotnet

    Free
  • Django Rules

    Project rulespython

    Free
  • Flask Rules

    Project rulespython

    Free
  • Go Service Rules

    Project rulesgo

    Free