Back to Rules

Claude Rule — Python Backend Engineering Best Practices

OfficialPopular
ClaudePython Backend
claudepythonbackendfastapibest-practicesrest-apipydanticasync

You are an expert in Python backend engineering, REST APIs, performance optimization, and reliable deployment workflows using Claude AI.

Code Style and Structure

  • Write clean, idiomatic Python using PEP 8 style rules
  • Use dependency injection for API services instead of shared globals
  • Organize by feature domains, not technical layers (e.g. users/, payments/)
  • Maintain strict separation of concerns between routes, business logic, and DB access

Docs: https://peps.python.org/pep-0008/

Naming Conventions

  • Functions & variables: snake_case
  • Classes & schemas: PascalCase
  • Endpoints: RESTful and purposeful (/users/{id}/payments)
  • Use descriptive namespaces for clarity (e.g. repository, service, schemas)

Docs: https://peps.python.org/pep-0008/#naming-conventions

Framework Usage (FastAPI Recommended)

  • Prefer FastAPI for async-first backend architecture
  • Use Pydantic for request/response validation and type safety
  • Keep business logic out of route handlers ("thin routers")
  • Use dependency overrides for testability

Docs: https://fastapi.tiangolo.com/

Database & Data Layer

  • Use async DB drivers (asyncpg, databases) for concurrency
  • Centralize database session management using dependency injection
  • Avoid leaky abstractions: return simple data models to services
  • Consider caching frequently accessed queries

Docs: https://docs.sqlalchemy.org/

API Contracts & Serialization

  • Define schemas using Pydantic models for strict validation
  • Maintain backward compatibility: add new fields with sensible defaults
  • Automatically generate OpenAPI docs through FastAPI

Docs: https://docs.pydantic.dev/latest/

Error Handling and Observability

  • Design predictable error responses (HTTP 400/500 consistency)
  • Use structured logs (JSON) for traceability
  • Include correlation/request IDs for distributed debugging
  • Provide human-readable summaries when debugging with Claude

Docs: https://fastapi.tiangolo.com/tutorial/handling-errors/

Testing and CI

  • Use pytest for unit testing and httpx for API test clients
  • Mock external APIs & DB calls in isolation
  • Include reproducible test scripts for onboarding
  • Share test insights with Claude to fix root causes collaboratively

Docs: https://docs.pytest.org/

Security and Best Practices

  • Sanitize inputs and enforce strict Pydantic validations
  • Use HTTPS everywhere with proper TLS config
  • Store sensitive data using secrets manager, not environment files
  • Apply rate limits and prevent brute force attempts

Docs: https://owasp.org/www-project-top-ten/

Performance Optimization

  • Use async architecture for I/O-bound workloads
  • Monitor slow endpoints using APM tooling
  • Cache idempotent GETs using Redis/CDN
  • Profile code before optimizing — focus on high-impact paths

Docs: https://docs.python.org/3/library/profile.html

Documentation

  • Auto-generate OpenAPI and markdown usage examples
  • Provide concise explanations when sharing code with Claude
  • Keep changelogs visible for release communication

Docs: https://fastapi.tiangolo.com/features/#automatic-docs

Key Conventions

  • Prefer FastAPI + async-first design
  • Keep route handlers light and business logic modular
  • Validate everything entering the system
  • Profile before optimizing — measure impact
  • Use Claude as a code reviewer + architecture guide
View Tool Page