Skip to content

thaithienvanid/python-fast-forge

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1 Commit
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Python FastAPI Boilerplate

Production-ready FastAPI boilerplate with clean architecture, comprehensive observability, and enterprise-grade features

Python 3.12+ FastAPI License: MIT Code style: Ruff

🎯 Overview

A production-grade FastAPI boilerplate designed for building scalable, maintainable APIs with enterprise features built-in. Perfect for SaaS applications, microservices, and complex business logic.

Built with:

  • πŸ—οΈ Clean Architecture - Clear separation of concerns across 4 layers
  • πŸ†” UUIDv7 - Time-ordered identifiers for distributed systems
  • 🏒 Multi-Tenancy - Built-in tenant isolation (JWT with ES256)
  • πŸ“Š Full Observability - OpenTelemetry, structured logging, distributed tracing
  • πŸ”„ Temporal Workflows - Durable task orchestration
  • βœ… Comprehensive Testing - 1,069 tests with 84% coverage β†’ detailed stats

⚑ Quick Start

Get running in 3 commands:

# 1. Install dependencies
pip install uv && uv sync --all-groups

# 2. Start services & run migrations
cp .env.example .env
docker-compose --profile infra up -d
make migrate

# 3. Start API
uv run python main.py
# β†’ API: http://localhost:8000
# β†’ Docs: http://localhost:8000/docs

πŸ‘‰ Complete setup guide | Tutorials | Architecture

πŸ“‹ Table of Contents

🎯 When to Use This

βœ… Perfect For

Use Case Why It Fits
SaaS Applications Multi-tenancy, security, scalability built-in
Microservices Clean architecture, distributed tracing, correlation IDs
Complex Business Logic Domain-driven design, clear layer separation
High-Performance APIs Async throughout, Redis caching, connection pooling
Team Collaboration Type safety, clear boundaries, comprehensive docs
Production Systems Observability, error handling, graceful degradation

❌ Probably Overkill For

  • Simple CRUD APIs - Too much structure for basic REST operations
  • Prototypes/MVPs - Consider simpler FastAPI templates for rapid experimentation
  • Learning Projects - Start with official FastAPI tutorials first
  • Single-page forms - Use lightweight frameworks

πŸ€” Decision Matrix

Your Requirement Use This Consider Alternative
Multi-tenancy required βœ… Yes ❌ No
>10K requests/day expected βœ… Yes 🀷 Maybe
Background jobs needed βœ… Yes ❌ No
Team size >3 developers βœ… Yes 🀷 Maybe
Complex business rules βœ… Yes ❌ No
Production deployment βœ… Yes 🀷 Maybe
Just learning FastAPI ❌ No βœ… Yes
Simple CRUD only ❌ No βœ… Yes

πŸš€ Features

Core Framework

  • ⚑ FastAPI - Modern async web framework with auto-generated docs
  • 🐍 Python 3.12-3.14 - Latest Python with type parameter syntax
  • πŸ—οΈ Clean Architecture - 4-layer architecture (Domain β†’ Application β†’ Infrastructure β†’ Presentation)
  • πŸ’‰ Dependency Injection - Container-based DI with dependency-injector
  • βœ… Type Safety - Full type hints throughout with MyPy validation

Data & Storage

  • πŸ—„οΈ PostgreSQL - Async database with SQLAlchemy 2.0
  • πŸ”„ Redis - High-performance caching with compression (zstd)
  • πŸ†” UUIDv7 - Time-ordered, sortable UUIDs for distributed systems
  • πŸ“„ Cursor Pagination - Efficient pagination for large datasets
  • πŸ”„ Database Migrations - Atlas for declarative schema management

Background Processing

  • βš™οΈ Temporal - Durable workflow orchestration with built-in observability
  • πŸ“¬ Email Service - Async email sending with Mailpit for dev/testing
  • πŸ”„ Async Tasks - Background job processing with retry logic

Security & Auth

  • πŸ” API Signature Validation - HMAC-SHA256 request signing for partner APIs
  • πŸ›‘οΈ Security Headers - CSP, HSTS, X-Frame-Options, etc.
  • 🚦 Rate Limiting - Per-client rate limiting with Redis
  • πŸ“‹ Log Sanitization - Automatic PII/secret removal from logs
  • πŸ”’ Tenant Isolation - Multi-tenant data segregation via JWT

Observability & Monitoring

  • πŸ“Š OpenTelemetry - Distributed tracing with OTLP export
  • πŸ“ Structured Logging - JSON logs with structlog
  • πŸ”— Correlation IDs - Cross-service request tracking
  • πŸ” Trace Context Propagation - W3C Trace Context standard
  • πŸ“Š Request Context - Extract client IP, trace IDs from headers

Developer Experience

  • πŸ§ͺ Comprehensive Testing β†’ detailed stats
  • 🎯 Test Factories - Reusable test data factories
  • πŸ”¬ Property-Based Testing - Hypothesis strategies for edge cases
  • πŸ“š Auto-Generated Docs - OpenAPI/Swagger UI
  • 🐳 Docker Support - Complete dev environment with docker-compose
  • πŸ”§ Pre-commit Hooks - Automated code quality (Ruff, MyPy)
  • ⚑ Fast Package Manager - UV for 10-100x faster dependency resolution

Resilience & Performance

  • πŸ”Œ Circuit Breaker - Fault tolerance for external services
  • πŸ’Ύ Redis Caching - Configurable TTL with compression
  • πŸ”„ Connection Pooling - Efficient database connection management
  • ♻️ Graceful Degradation - Fallback strategies for service failures

πŸ›οΈ Architecture

This boilerplate follows Clean Architecture principles with clear separation of concerns:

graph TB
    Presentation["Presentation Layer<br/>FastAPI routes, schemas, DTOs"]
    Application["Application Layer<br/>Use cases, orchestration, workflows"]
    Infrastructure["Infrastructure Layer<br/>Database, cache, external APIs, implementations"]
    Domain["Domain Layer<br/>Entities, value objects, business rules"]

    Presentation --> Application
    Application --> Domain
    Infrastructure --> Domain

    style Presentation fill:#e1f5ff
    style Application fill:#fff4e1
    style Domain fill:#f0ffe1
    style Infrastructure fill:#ffe1f5
Loading

Key principles:

  • Dependency Inversion - Inner layers don't depend on outer layers
  • Single Responsibility - Each layer has one clear purpose
  • Interface Segregation - Use interfaces/protocols for dependencies
  • Repository Pattern - Abstract data access
  • Unit of Work - Manage transactions consistently

πŸ‘‰ Complete architecture guide | Design decisions

πŸ“š Documentation

Getting Started

How-To Guides (Task-Oriented)

Reference (Technical Specs)

Explanation (Deep Dives)

πŸ› οΈ Technology Stack

Core

Technology Version Purpose
Python 3.12-3.14 Programming language
FastAPI 0.121+ Web framework
Pydantic 2.12+ Data validation
SQLAlchemy 2.0+ ORM & database toolkit
PostgreSQL 16+ Primary database
Redis 7+ Caching & rate limiting

Infrastructure

Technology Version Purpose
Temporal 1.8+ Workflow orchestration
OpenTelemetry 1.38+ Distributed tracing
Atlas Latest Database schema migrations
UV Latest Fast package manager
Docker Latest Containerization

Development

Technology Version Purpose
Pytest 8.4+ Testing framework
Ruff 0.14+ Linting & formatting
MyPy 1.18+ Static type checking
Pre-commit 4.3+ Git hooks
Hypothesis Latest Property-based testing

πŸ“ Project Structure

python-fast-forge/
β”œβ”€β”€ src/                           # Source code
β”‚   β”œβ”€β”€ domain/                    # Domain layer (entities, business rules)
β”‚   β”‚   β”œβ”€β”€ models/                # Domain models
β”‚   β”‚   β”œβ”€β”€ exceptions.py          # Domain exceptions
β”‚   β”‚   └── pagination.py          # Pagination value objects
β”‚   β”œβ”€β”€ app/                       # Application layer (use cases)
β”‚   β”‚   β”œβ”€β”€ usecases/              # Business use cases
β”‚   β”‚   └── tasks/                 # Background tasks
β”‚   β”œβ”€β”€ infrastructure/            # Infrastructure layer (implementations)
β”‚   β”‚   β”œβ”€β”€ persistence/           # Database (SQLAlchemy)
β”‚   β”‚   β”œβ”€β”€ repositories/          # Data access repositories
β”‚   β”‚   β”œβ”€β”€ cache/                 # Redis caching
β”‚   β”‚   β”œβ”€β”€ security/              # Security implementations
β”‚   β”‚   β”œβ”€β”€ telemetry/             # OpenTelemetry setup
β”‚   β”‚   └── patterns/              # Circuit breaker, etc.
β”‚   β”œβ”€β”€ presentation/              # Presentation layer (API)
β”‚   β”‚   β”œβ”€β”€ api/                   # FastAPI routes
β”‚   β”‚   β”œβ”€β”€ schemas/               # Request/response DTOs
β”‚   β”‚   └── mappers/               # DTO ↔ Domain mapping
β”‚   β”œβ”€β”€ external/                  # External service clients
β”‚   β”œβ”€β”€ utils/                     # Shared utilities
β”‚   └── container.py               # Dependency injection container
β”œβ”€β”€ tests/                         # Test suite
β”‚   β”œβ”€β”€ unit/                      # Unit tests (19 files)
β”‚   β”œβ”€β”€ integration/               # Integration tests (9 files)
β”‚   β”œβ”€β”€ factories.py               # Test data factories
β”‚   └── strategies.py              # Hypothesis strategies
β”œβ”€β”€ migrations/                    # Atlas database migrations (SQL)
β”œβ”€β”€ load_models.py                 # SQLAlchemy model loader for Atlas
β”œβ”€β”€ atlas.hcl                      # Atlas migration configuration
β”œβ”€β”€ config/                        # Configuration files
β”œβ”€β”€ docs/                          # Documentation
β”‚   β”œβ”€β”€ tutorials/                 # Step-by-step tutorials
β”‚   β”œβ”€β”€ how-to/                    # Task-oriented guides
β”‚   β”œβ”€β”€ reference/                 # Technical reference
β”‚   └── explanation/               # Deep dives & ADRs
β”œβ”€β”€ main.py                        # API entry point
β”œβ”€β”€ worker.py                      # Temporal worker
β”œβ”€β”€ docker-compose.yml             # Dev environment
└── pyproject.toml                 # Project configuration

πŸš€ Getting Started

Prerequisites

Installation

# 1. Clone repository
git clone https://github.com/thaithienvanid/python-fast-forge.git
cd python-fast-forge

# 2. Install UV (fast package manager)
pip install uv

# 3. Install all dependencies (dev, test, security tools)
uv sync --all-groups

# 4. Copy environment file
cp .env.example .env

# 5. Start infrastructure (PostgreSQL, Redis, Temporal, Mailpit)
docker-compose --profile infra up -d

# 6. Install Atlas CLI (one-time setup)
curl -sSf https://atlasgo.sh | sh

# 7. Run database migrations
make migrate

# 8. Start API server (with hot reload)
uv run python main.py

# 8. (Optional) Start Temporal worker in another terminal
uv run python worker.py

Verify Installation

# Check API health
curl http://localhost:8000/health

# Expected response:
# {"status":"healthy","version":"0.1.0"}

# Visit interactive docs
open http://localhost:8000/docs

Access Services

Service URL Purpose
API http://localhost:8000 Main API
API Docs http://localhost:8000/docs Swagger UI
ReDoc http://localhost:8000/redoc Alternative docs
Mailpit http://localhost:8025 Email testing
Temporal UI http://localhost:8080 Workflow dashboard
PostgreSQL localhost:5432 Database
Redis localhost:6379 Cache

πŸ§ͺ Testing

# Run all tests
make test

# Run with coverage report
make test-cov

# Run only unit tests
uv run pytest tests/unit/

# Run only integration tests
uv run pytest tests/integration/

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

# Run tests in parallel (faster)
uv run pytest -n auto

πŸ‘‰ Complete testing guide

πŸ”§ Development

# Install pre-commit hooks (auto-format, lint, type-check)
uv run pre-commit install

# Run linting
make lint

# Run type checking
make type-check

# Format code
make format

# Create new migration
make migrate-create m="Description"

# View migration status
make migrate-status

# Inspect schema
make schema-inspect

πŸ‘‰ Development workflow guide

πŸ“¦ Deployment

This boilerplate is production-ready with:

  • βœ… Docker multi-stage builds
  • βœ… Health checks
  • βœ… Graceful shutdown
  • βœ… Environment-based configuration
  • βœ… Secrets management
  • βœ… Horizontal scaling support
# Build production image
docker build -f Dockerfile -t my-api:latest .

# Run in production mode
docker-compose --profile infra --profile app up -d

πŸ‘‰ Complete deployment guide

🀝 Contributing

We welcome contributions! Please see our Contributing Guide for details.

Quick links:

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ™ Acknowledgments

Built with these amazing technologies:

πŸ“ž Support & Community


⭐ Star this repo if you find it helpful!

About

A comprehensive FastAPI template featuring clean architecture, multi-tenancy, OpenTelemetry tracing, Temporal workflows, and enterprise-grade patterns. Perfect for building scalable APIs, SaaS applications, and microservices with Python 3.12+.

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages