Skip to content

AH-Toby/fastapi-boilerplate

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

FastAPI Boilerplate

A production-ready FastAPI boilerplate with async support, clean architecture, and modern development tools.

Features

  • 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

Quick Start

Prerequisites

  • Python 3.12+
  • PostgreSQL 12+
  • Redis 6+
  • uv (recommended) or pip

Installation

# Clone the repository
git clone <repository-url>
cd fastapi-boilerplate

# Install dependencies with uv
uv sync

# Or with pip
pip install -e .

Configuration

# Copy environment template
cp backend/.env.example backend/.env

# Edit configuration
vim backend/.env

Key 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

Running

# Development mode
cd backend
python run.py

# Or with uvicorn directly
uvicorn backend.main:app --reload --host 0.0.0.0 --port 8000

The API will be available at http://localhost:8000

API documentation: http://localhost:8000/docs

Project Structure

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

Architecture

Layered Design

┌─────────────────────────────────────────┐
│  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    │
└─────────────┘    └─────────────┘

Key Components

  • 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

Core Features

1. Logging System

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)

2. Context Management

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.country

3. Unified Response Format

Consistent API responses:

{
    "code": 200,
    "status": "SUCCESS",
    "message": "Operation successful",
    "data": {...}
}

4. Snowflake ID Generation

Distributed unique ID generation:

from backend.utils.snowflake import get_snowflake_id

unique_id = await get_snowflake_id()

Documentation

Detailed documentation is available in the docs/ directory:

  1. 开发规范 - Development specifications and import rules
  2. 项目结构 - Detailed project structure and architecture
  3. 日志系统 - Logging system architecture and configuration
  4. 上下文系统 - Context management system
  5. 时区控制 - Timezone handling
  6. 雪花算法 - Snowflake ID generator
  7. 数据库三层base - Database base classes

Development

Code Style

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

Adding New Modules

  1. Create module structure under backend/app/
  2. Follow the layered architecture (api/crud/models/schema/service)
  3. Register routes in backend/app/router.py
  4. Add configuration if needed in backend/configs/

Dependencies

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.

License

MIT License

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

About

A production-ready FastAPI boilerplate with async support, clean architecture, and modern development tools.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages