A production-ready FastAPI boilerplate with async support, clean architecture, and modern development tools.
- Async-First Architecture: Built on FastAPI with full async/await support for high-performance APIs
- Clean Layered Design: Pseudo-three-tier architecture (API → Service → CRUD) inspired by Spring Boot
- Advanced Logging: Structured logging with loguru, automatic request ID tracking, and JSON output support
- Context Management: Request-scoped context system for seamless data access across layers
- Database Ready: SQLAlchemy 2.0+ with async PostgreSQL support and connection pooling
- Redis Integration: Built-in Redis support with async operations
- Timezone Handling: Automatic timezone conversion and UTC storage
- Snowflake ID Generator: Distributed unique ID generation with Redis coordination
- Type Safety: Full Pydantic v2 integration with strict type checking
- Environment-Aware: Configuration management with pydantic-settings and .env support
- Production Optimized: Log rotation, compression, error tracking, and performance monitoring
- Python 3.12+
- PostgreSQL 12+
- Redis 6+
- uv (recommended) or pip
# Clone the repository
git clone <repository-url>
cd fastapi-boilerplate
# Install dependencies with uv
uv sync
# Or with pip
pip install -e .# Copy environment template
cp backend/.env.example backend/.env
# Edit configuration
vim backend/.envKey configuration options:
# Database
DB_HOST=localhost
DB_PORT=5432
DB_DATABASE=your_database
DB_USERNAME=postgres
DB_PASSWORD=your_password
# Redis
REDIS_HOST=localhost
REDIS_PORT=6379
# Timezone
DATETIME_TIMEZONE=Asia/Shanghai
# Logging
LOG_STD_LEVEL=INFO
LOG_JSON_ENABLED=false# Development mode
cd backend
python run.py
# Or with uvicorn directly
uvicorn backend.main:app --reload --host 0.0.0.0 --port 8000The API will be available at http://localhost:8000
API documentation: http://localhost:8000/docs
fastapi-boilerplate/
├── backend/
│ ├── app/ # Business logic modules
│ │ ├── auth/ # Authentication module
│ │ │ ├── api/ # Route handlers
│ │ │ ├── crud/ # Database operations
│ │ │ ├── models/ # SQLAlchemy models
│ │ │ ├── schema/ # Pydantic schemas
│ │ │ └── service/ # Business logic
│ │ └── router.py # Main router aggregator
│ ├── common/ # Shared components
│ │ ├── exception/ # Custom exceptions
│ │ └── response/ # Unified response format
│ ├── configs/ # Configuration modules
│ ├── core/ # Core infrastructure
│ │ ├── registrar/ # Application registrar
│ │ ├── db_engine.py # Database engine
│ │ ├── redis_engine.py # Redis engine
│ │ └── logger.py # Logging setup
│ ├── middleware/ # Custom middleware
│ ├── models/ # Base models
│ ├── utils/ # Utility functions
│ ├── main.py # FastAPI app factory
│ └── run.py # Application entry point
├── docs/ # Documentation
└── pyproject.toml # Project dependencies
┌─────────────────────────────────────────┐
│ API Layer (router.py) │ ← Route definitions, validation
├─────────────────────────────────────────┤
│ Service Layer (service/) │ ← Business logic, orchestration
├─────────────────────────────────────────┤
│ CRUD Layer (crud/) │ ← Database operations
├─────────────────────────────────────────┤
│ Model Layer (models/) │ ← SQLAlchemy models
└─────────────────────────────────────────┘
↕ ↕
┌─────────────┐ ┌─────────────┐
│ PostgreSQL │ │ Redis │
└─────────────┘ └─────────────┘
- Registrar System: Centralized application initialization and component registration
- Context System: Request-scoped data access without parameter passing
- Logging System: Unified logging with automatic request tracking
- Response Format: Standardized API responses with error handling
Advanced logging with loguru featuring:
- Automatic request ID injection
- Separate access and error logs
- Log rotation and compression
- JSON output for production
- SQLAlchemy query logging
from backend.core.logger import log
log.info("User logged in", user_id=123)
log.error("Payment failed", order_id=456, exc_info=True)Request-scoped context for seamless data access:
from backend.core.context import ctx
# Access anywhere in your code
user_id = ctx.user_id
ip_address = ctx.ip
country = ctx.countryConsistent API responses:
{
"code": 200,
"status": "SUCCESS",
"message": "Operation successful",
"data": {...}
}Distributed unique ID generation:
from backend.utils.snowflake import get_snowflake_id
unique_id = await get_snowflake_id()Detailed documentation is available in the docs/ directory:
- 开发规范 - Development specifications and import rules
- 项目结构 - Detailed project structure and architecture
- 日志系统 - Logging system architecture and configuration
- 上下文系统 - Context management system
- 时区控制 - Timezone handling
- 雪花算法 - Snowflake ID generator
- 数据库三层base - Database base classes
Follow the import rules defined in development specifications:
- Use absolute imports for cross-module references
- Relative imports only within the same subpackage
- No bare top-level imports
- Create module structure under
backend/app/ - Follow the layered architecture (api/crud/models/schema/service)
- Register routes in
backend/app/router.py - Add configuration if needed in
backend/configs/
Core dependencies:
- FastAPI - Modern web framework
- SQLAlchemy - Async ORM
- asyncpg - PostgreSQL async driver
- Redis - Caching and distributed coordination
- Pydantic - Data validation
- loguru - Advanced logging
- uvicorn - ASGI server
See pyproject.toml for complete dependency list.
Contributions are welcome! Please feel free to submit a Pull Request.