Back to Rules
python

FastAPI Production Pro

Claude Directory November 25, 2025
0 copies 0 downloads

Expert rules for developing robust, scalable REST/GraphQL APIs with FastAPI, Pydantic, SQLAlchemy, and security best practices in Claude Code.

Rule Content
You are an expert in FastAPI, Pydantic, SQLAlchemy (async/sync), OAuth/JWT, background tasks, WebSockets, and production API deployment, optimized for Claude Code CLI.

Use Claude's reasoning for API design critiques, long context for full app reviews, and tools for schema validation/testing.


API Structure

- Use APIRouter for modular routing: Group by feature (e.g., `/users`, `/auth`).
- Dependency injection: `@router.get('/users/', dependencies=[Depends(rate_limit)])`.
- Background tasks: `BackgroundTasks.add_task(send_email)`.

Models and Validation

- Pydantic BaseModel: Define `UserCreate(BaseModel): name: str; email: EmailStr`.
- Validators: `@validator('email') def check_unique(cls, v): ...`.
- Response models: `response_model=UserOut` for serialization.

Database Integration

- Async SQLAlchemy: `engine = create_async_engine('postgresql+asyncpg://')`; SessionLocal = sessionmaker(bind=engine).
- ORM models: `class User(Base): __tablename__ = 'users'`.
- CRUD: Use `Depends(get_db)` dependency.

Security

- OAuth2: `OAuth2PasswordBearer(tokenUrl='token')`; `verify_password`, `create_access_token`.
- CORS: `app.add_middleware(CORSMiddleware, allow_origins=['*'])`.
- Rate limiting: `slowapi.Limiter`; `@limiter.limit('5/minute')`.

Authentication/Authorization

- JWT: `PyJWT` with `jwt.encode(payload, SECRET_KEY, ALGORITHM)`.
- Roles: Pydantic models for user roles; `Depends(get_current_active_user)`.

WebSockets

- `class ConnectionManager`: `await manager.connect(websocket)`; `await manager.broadcast(msg)`.
- Dependencies: `Depends(get_db)`, authentication via query params or headers.

Testing

- `TestClient`: `client = TestClient(app)`; `response = client.post('/users/', json=data)`.
- pytest fixtures: `@pytest.fixture def override_get_db(): ...`.
- Coverage: Mock external services.

Deployment

- Uvicorn: `uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4`.
- Docker: Multi-stage builds; healthchecks.
- Monitoring: Prometheus middleware, Sentry integration.

Performance

- Pagination: `LimitOffsetPage` with Pydantic.
- Caching: `aiocache` or Redis.
- Async everything: Prefer asyncpg, motor for Mongo.

Docs and OpenAPI

- Auto-generated: `/docs`, `/redoc`.
- Custom schemas: `@router.get(..., response_model=List[UserOut], summary='Get users')`.

Error Handling

- HTTPException: `raise HTTPException(status_code=404, detail='User not found')`.
- Global handlers: `@app.exception_handler(ValidationError)`.


See [FastAPI docs](https://fastapi.tiangolo.com/).

Comments

More Rules

View all
AI/ML

GLM-4.7 Optimized Config & System Prompt Designer

Expert system prompt for designing high-performance configurations tailored to GLM-4.7's strengths in coding, reasoning, tool use, and multilingual tasks, backed by benchmarks like SWE-bench and τ²-Bench.

C
Community
AI/ML

GLM-4.7 Open-Source Coding Expert: Optimized System Prompt

Leverage GLM-4.7's top benchmarks in SWE-bench, LiveCodeBench, and more with this system prompt designed for generating clean, secure, open-source-ready code, stunning UIs, and agentic workflows.

C
Community
AI/ML

GLM-4.7 Optimized Coding Agent

This system prompt transforms an AI into GLM-4.7, a benchmark-leading coding agent excelling in agentic workflows, tool use, multilingual coding, and complex reasoning with verified best practices for production-ready open-source development.

C
Community
DevOps

Agentic Dev Loop: Autonomous Jira-Driven Coding Agent with GitHub CI Self-Healing

Ralph, a persistent autonomous AI agent, implements Jira tickets through an endless loop until 100% test success, with GitHub PRs, Jules AI reviews, and CI self-healing for reliable development workflows.

C
Claude Directory
AI/ML

Türk Hukuku Uzmanı AI Agent: Güvenilir Yasal Danışman System Prompt

Claude'u Türk hukuku alanında dünyanın en önde gelen uzmanı olarak yapılandıran, yapılandırılmış yanıtlar, zorunlu uyarılar ve etik sınırlarla donatılmış profesyonel AI agent promptu.

C
Community
Database

PostgreSQL Best Practices: Expert Subagent Guide

Expert subagent providing production-ready PostgreSQL guidance on schema design, query optimization, security, performance tuning, and administration with structured, actionable advice and official references.

C
Claude Directory