CLAUDE.mdpython

FastAPI-Template CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

View Source

CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

Project Overview

This is an enterprise-grade FastAPI backend template with a clean three-layer architecture (API โ†’ Service โ†’ Repository โ†’ Model). It includes built-in RBAC permission management, user management, file management, and other core enterprise features. The project uses UV for package management and focuses on providing a clean, extensible backend framework.

Common Commands

Environment Setup

# Install UV package manager (if not installed)
curl -LsSf https://astral.sh/uv/install.sh | sh

# Install project dependencies
uv sync

# Install development dependencies
uv sync --dev

Development Server

# Run development server with hot reload
uv run uvicorn src:app --reload --host 0.0.0.0 --port 8000

# Run production server
uv run uvicorn src:app --host 0.0.0.0 --port 8000 --workers 4

Database Operations

# Initialize database (first time setup)
uv run aerich init-db

# Generate migration after model changes
uv run aerich migrate --name "describe_your_changes"

# Apply migrations
uv run aerich upgrade

# View migration history
uv run aerich history

Testing

# Run all tests
uv run pytest

# Run specific test file
uv run pytest tests/test_users.py

# Run with coverage report
uv run pytest --cov=src --cov-report=html

Code Quality

๐Ÿ”ง Pre-commit Hooks (่‡ชๅŠจๅŒ–)

# hooks ไผšๅœจ uv sync ๆ—ถ่‡ชๅŠจๅฎ‰่ฃ…ๅนถ้…็ฝฎ
# ๆฏๆฌก git commit ๆ—ถ่‡ชๅŠจ่ฟ่กŒ๏ผŒ็กฎไฟไปฃ็ ่ดจ้‡

# ๆ‰‹ๅŠจ่ฟ่กŒๆ‰€ๆœ‰ๆฃ€ๆŸฅ
uv run pre-commit run --all-files

# ็ฆ็”จ hooks (ๅฆ‚ไธ้œ€่ฆ)
uv run pre-commit uninstall

# ่ทณ่ฟ‡ๅ•ๆฌกๆฃ€ๆŸฅ (็ดงๆ€ฅๆไบค)
git commit --no-verify -m "urgent fix"

โš™๏ธ ๆ‰‹ๅŠจๆฃ€ๆŸฅๅ‘ฝไปค

# ไปฃ็ ๆฃ€ๆŸฅๅ’Œ่‡ชๅŠจไฟฎๅค (ๆ›ฟไปฃ black + isort)
uv run ruff check --fix src/

# ไปฃ็ ๆ ผๅผๅŒ–
uv run ruff format src/

# ็ฑปๅž‹ๆฃ€ๆŸฅ (ๅฏ้€‰)
uv run mypy src/

๐Ÿ“– ่ฏฆ็ป†้…็ฝฎ: ๆŸฅ็œ‹ docs/pre-commit-guide.md

Docker Operations

# Build image
docker build -t backend-template .

# Run container
docker run -p 8000:8000 backend-template

Documentation

# Install documentation dependencies
uv sync --group docs

# Serve documentation locally
uv run mkdocs serve

# Build documentation
uv run mkdocs build

# Deploy documentation to GitHub Pages
uv run mkdocs gh-deploy

Architecture Overview

The project follows a clean three-layer architecture with clear separation of concerns:

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                        API Layer                            โ”‚
โ”‚  (src/api/v1/) - Routes, parameter validation, responses    โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                              โ†“
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                      Service Layer                          โ”‚
โ”‚  (src/services/) - Business logic, permissions, validation  โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                              โ†“
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                   Repository Layer                          โ”‚
โ”‚  (src/repositories/) - Data access, CRUD operations         โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                              โ†“
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                      Model Layer                            โ”‚
โ”‚  (src/models/) - Tortoise ORM models, database schemas     โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Key Design Principles

  • Single Responsibility: Each layer handles only its own logic
  • Dependency Injection: Managed through FastAPI's dependency system
  • Type Safety: Comprehensive Python type annotations throughout
  • Async First: All I/O operations are asynchronous
  • Security First: Multiple built-in security mechanisms

Core Components

  • Authentication: JWT-based with access tokens (4 hours) and refresh tokens (7 days)
  • Authorization: RBAC system with roles, menus, and API permissions
  • Rate Limiting: Login throttling (5 attempts/minute) and refresh token limiting (10/minute)
  • File Management: Secure file upload/download with type validation and size limits
  • Audit Logging: Comprehensive user activity tracking
  • Caching: Redis integration with smart caching strategies

Development Workflow for New Features

When adding new functionality, follow this standard process:

  1. Define Model (src/models/admin.py) - Create Tortoise ORM model
  2. Create Schema (src/schemas/) - Define Pydantic validation schemas
  3. Implement Repository (src/repositories/) - Add data access layer
  4. Write Service (src/services/) - Implement business logic
  5. Add API Routes (src/api/v1/) - Create endpoint handlers
  6. Generate Migration - Run uv run aerich migrate --name "feature_name"
  7. Write Tests (tests/) - Add test coverage

Security Considerations

  • JWT tokens are configured with HS256 algorithm
  • Default admin credentials: username=admin, password=abcd1234 (change immediately!)
  • Password requirements: minimum 8 characters with letters and numbers
  • File upload restrictions: whitelist validation, size limits, dangerous file detection
  • Production checklist:
    • Set DEBUG=False
    • Generate strong SECRET_KEY with openssl rand -hex 32
    • Configure proper CORS_ORIGINS
    • Use PostgreSQL instead of SQLite
    • Set strong SWAGGER_UI_PASSWORD

Database Best Practices

  • Models inherit from BaseModel and TimestampMixin for consistency
  • Use select_related() for foreign key preloading
  • Use prefetch_related() for many-to-many optimization
  • Add indexes on frequently queried fields
  • String references for relationships to avoid circular imports: fields.ForeignKeyField("models.User")

Environment Configuration

Key environment variables (configured in .env):

  • SECRET_KEY: JWT signing key (required, auto-generated if missing)
  • APP_ENV: development/production
  • DB_ENGINE: sqlite/postgres
  • CORS_ORIGINS: Allowed origins for CORS
  • JWT_ACCESS_TOKEN_EXPIRE_MINUTES: Access token expiry (default: 240)
  • JWT_REFRESH_TOKEN_EXPIRE_DAYS: Refresh token expiry (default: 7)

Important Notes

  • All routes are async - use await for database operations
  • Repository pattern is used for data access - avoid direct model queries in services
  • Services handle business logic and permissions - keep routes thin
  • Use dependency injection for authentication: current_user: User = DependAuth
  • For admin-only endpoints use: current_user: User = SuperUserRequired
  • When modifying models, always generate and apply migrations
  • The project uses UV for dependency management - avoid pip directly

API Documentation

After starting the server:

  • Swagger UI: http://localhost:8000/docs
  • ReDoc: http://localhost:8000/redoc
  • Health check: http://localhost:8000/api/v1/base/health
  • Version info: http://localhost:8000/api/v1/base/version