Skip to content

A production-ready FastAPI-based backend API framework that follows best practices for building high-performance web APIs.

Notifications You must be signed in to change notification settings

yuansir/fastapi-startup-template

Repository files navigation

FastAPI Startup Template

English | δΈ­ζ–‡

A production-ready FastAPI-based backend API framework that follows best practices for building high-performance web APIs.

✨ Features

  • Modular Architecture: Organized by functional domains for better maintainability
  • Developer Management: Developer registration and information management
  • API Key Management: Secure API key generation, distribution, and lifecycle management
  • JWT Authentication: JWT-based request authentication mechanism
  • Async Support: Full utilization of FastAPI's asynchronous capabilities for better performance
  • ORM Integration: Integrated with Tortoise ORM for powerful async database operations
  • Environment Configuration: Flexible multi-environment configuration system
  • Logging System: Integrated Loguru for elegant logging
  • CLI Tools: Complete command-line toolset for managing developers, API keys, and database migrations

πŸš€ Quick Start

Prerequisites

  • Python 3.8+
  • MySQL 5.7+
  • Poetry (Python dependency management tool)
  • Docker and Docker Compose (optional, for containerized deployment)

Installation

# Install project dependencies
poetry install

# Method 1: Use poetry run (recommended for all Poetry versions)
poetry run python -m src

# Method 2: Manually activate virtual environment (if you need to run multiple commands in the venv)
source $(poetry env info --path)/bin/activate

Environment Variables

Copy .env.example to .env and configure according to your environment:

# Application settings
APP_NAME=fastapi-base-framework
HOST=0.0.0.0
PORT=8000
WORKERS_COUNT=1
RELOAD=True
ENVIRONMENT=development
DEBUG=True
LOG_LEVEL=INFO

# Database settings
DB_HOST=localhost
DB_PORT=3306
DB_USER=root
DB_PASSWORD=
DB_BASE=fastapi_base
DB_ECHO=False

# JWT settings
SECRET_KEY=replace-with-secure-secret-key
JWT_SECRET=replace-with-secure-jwt-secret
JWT_ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=1440

Initialize Database

# Create database
mysql -u root -e "CREATE DATABASE IF NOT EXISTS fastapi_base CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"

# Initialize database structure
python scripts/init_db.py

# Or use CLI tools step by step

# Initialize database migration environment
python -m src.cli.main db init

# Generate migration files
python -m src.cli.main db migrate "Initial migration"

# Apply migrations
python -m src.cli.main db upgrade

Run Development Server

poetry run python -m src

After starting the service, you can access:

🐳 Running with Docker

Development Mode

docker-compose -f docker-compose.yml -f deploy/docker-compose.dev.yml up --build

Production Mode

docker-compose up -d --build

πŸ› οΈ CLI Tools Guide

This project provides a powerful command-line tool for managing developers, API keys, database migrations, and more. The CLI tool is built with Typer, offering a user-friendly command-line interface with detailed help information.

Basic Usage

# Show main help and available commands
python -m src.cli

# Or use Poetry
poetry run python -m src.cli

Developer Management Commands

# Show developer command help
python -m src.cli developer --help

# List all developers
python -m src.cli developer list

# Add a new developer
python -m src.cli developer add --name "Developer Name" --email "developer@example.com"
# Shorthand
python -m src.cli developer add -n "Developer Name" -e "developer@example.com"

# Get developer details
python -m src.cli developer get 1

# Update developer information
python -m src.cli developer update 1 --name "New Name" --email "new-email@example.com"

# Delete a developer
python -m src.cli developer delete 1
# Skip confirmation
python -m src.cli developer delete 1 -y

API Key Management Commands

# Show API key command help
python -m src.cli api-key --help

# List all API keys for a developer
python -m src.cli api-key list 1

# Create a new API key for a developer
python -m src.cli api-key create 1

# Revoke an API key
python -m src.cli api-key revoke 123
# Skip confirmation
python -m src.cli api-key revoke 123 -y

πŸ”§ Database Migration with Aerich

This project uses Aerich for database migration management. Below are the detailed usage instructions.

Initialize Database

When running the project for the first time, you need to initialize the database structure. We provide two approaches:

  1. Using the initialization script (recommended for first-time setup):

    python scripts/init_db.py
  2. Using CLI tools (for more control):

    # Initialize migration environment
    python -m src.cli.main db init
    
    # Generate migration files
    python -m src.cli.main db migrate "Initial migration"
    
    # Apply migrations
    python -m src.cli.main db upgrade

Common Migration Commands

Check migration status

python -m src.cli.main db history

Rollback migrations

# Rollback to the previous version
python -m src.cli.main db downgrade

# Or rollback to a specific version
python -m src.cli.main db downgrade "version_name"

View database model structure

python -m src.cli.main db show-models

Aerich Configuration

The aerich.ini file in the project root defines Aerich's configuration:

[aerich]
tortoise_orm = src.db.config.TORTOISE_CONFIG
location = ./migrations
src_folder = ./

πŸ§ͺ Testing

Run tests:

# Start test database
docker run -p 3306:3306 -e MYSQL_ROOT_PASSWORD=test -e MYSQL_DATABASE=test_db -d mysql:8.4

# Run tests
pytest -vvs tests/

πŸ“¦ Deployment

Production Environment Variables

Create a .env.prod file and configure production environment variables:

ENVIRONMENT=production
DEBUG=False
DB_PASSWORD=your_secure_production_password
SECRET_KEY=your_secure_secret_key
JWT_SECRET=your_secure_jwt_secret
# Other production configurations...

Deploy with Docker Compose

docker-compose -f docker-compose.yml -f deploy/docker-compose.prod.yml up -d

Run with Gunicorn

gunicorn src.gunicorn_runner:app --workers 4 --worker-class uvicorn.workers.UvicornWorker --bind 0.0.0.0:8000

πŸ”’ Security Best Practices

  • Use strong passwords and keys in production
  • Enable HTTPS for secure communication
  • Rotate API keys and JWT secrets regularly
  • Implement rate limiting to prevent abuse
  • Use authentication and authorization for all sensitive operations

πŸ“‹ FastAPI Best Practices

This framework follows FastAPI best practices:

  1. Modular Routing: Organized by functional domains
  2. Dependency Injection: For authentication and parameter validation
  3. Pydantic Models: Clear data models for requests and responses
  4. Async Processing: Leverage async features for better performance
  5. Auto-generated Documentation: Utilize FastAPI's automatic documentation

🀝 Contributing

Contributions are welcome! Please feel free to submit pull requests, report issues, or suggest improvements. Make sure to follow the project's code style and contribution guidelines.

About

A production-ready FastAPI-based backend API framework that follows best practices for building high-performance web APIs.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published