WINDSURF RULES BACKEND / API FastAPI

Python FastAPI Backend Rules

Rules for building clean FastAPI backends with typed routes, Pydantic models, validation, services, and error handling.

Python FastAPI API Backend Pydantic Cursor Claude Code
Tool
Windsurf
Asset type
Rules
Category
Backend / API
Framework
FastAPI
Recommended path
.devin/rules/fastapi-python-backend.md
Activation / Trigger
always_on (default)
License
MIT
Last updated
2026-07-08

How to use this asset

  1. Click Copy Rule above to copy the full rule text.
  2. Save as Markdown under .devin/rules/*.md (preferred) or .windsurf/rules/*.md, or paste via Cascade → Customizations → Rules.
  3. Windsurf reads workspace rules from .devin/rules/ on each Cascade session.

Compatible tools

Designed for Windsurf. Also works with: Claude Code.

Asset content

# Python FastAPI Backend Rules

You are an expert Python backend developer using FastAPI.

## Application Layout
- Structure as `app/main.py`, `routers/`, `services/`, `schemas/`, `models/`, `dependencies/`
- Register routers with prefixes and tags for OpenAPI grouping
- Keep endpoints thin — validate input, call service, map response
- Share settings via Pydantic `BaseSettings` loaded from environment

## Routes & Schemas
- Define request and response models with Pydantic v2; use `response_model` on decorators
- Return appropriate status codes (`201` create, `204` delete, `422` validation)
- Document endpoints with summary and description for auto-generated OpenAPI
- Version public APIs under `/api/v1`

## Validation & Errors
- Validate all external input at the boundary; never trust query or path params
- Raise `HTTPException` with stable error codes; use exception handlers for domain errors
- Log stack traces server-side only
- Use dependency injection for DB sessions, current user, and permissions

## Async & Data Access
- `async def` for I/O-bound work; avoid blocking calls inside async routes
- Pool database connections; close sessions in dependencies or context managers
- Wrap multi-step writes in transactions

## Security & Testing
- Authenticate with OAuth2/JWT patterns from `fastapi.security`
- Rate-limit sensitive routes; sanitize file uploads
- Integration tests with `TestClient` and mocked external services
- Test validation failures and authorization denials explicitly

Save as Markdown under .devin/rules/*.md (preferred) or .windsurf/rules/*.md, or paste via Cascade → Customizations → Rules.