Skip to content

Repository files navigation

FastAPI Template

A production-ready FastAPI boilerplate designed for rapid project setup β€” featuring clean architecture, Docker support, CI/CD, logging and INI-based configuration.

Features

  • ⚑ FastAPI with Python 3.13
  • 🐳 Docker & Docker Compose for development and production
  • πŸ”„ CI/CD pipeline with GitHub Actions
  • πŸ—„οΈ PostgreSQL database with SQLAlchemy
  • πŸ”΄ Redis for caching
  • πŸ”’ Nginx reverse proxy with rate limiting
  • πŸ“ Alembic for database migrations
  • πŸ§ͺ Pytest for testing
  • πŸ“Š Logging configured and ready to use
  • πŸ”§ Makefile for convenient development

Quick Start

Prerequisites

  • Docker and Docker Compose
  • Python 3.13+ (for local development)
  • Make (optional)

Installation

  1. Clone the repository:
git clone <your-repo-url>
cd fastapi-template
  1. Create config.ini file from example:
cp config.ini.example config.ini
  1. Edit config.ini file according to your needs

Running (Development)

Using Docker Compose:

make dev
# or
docker compose -f docker/docker-compose.dev.yml up --build

Locally (without Docker):

python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
pip install -r requirements.txt
python src/main.py
# or
uvicorn src.main:app --reload

Application will be available at: http://localhost:8000

API documentation:

Running (Production)

make up
# or
docker compose -f docker/docker-compose.yml up -d

Project Structure

fastapi-template/
β”œβ”€β”€ .github/
β”‚   └── workflows/
β”‚       └── develop.yaml          # CI/CD pipeline
β”œβ”€β”€ src/                          # Source code
β”‚   β”œβ”€β”€ main.py                   # FastAPI application entry point
β”‚   β”œβ”€β”€ config.py                 # Configuration loader (INI files)
β”‚   β”œβ”€β”€ dependencies.py           # Global dependencies
β”‚   β”œβ”€β”€ schemas.py                # Shared Pydantic schemas
β”‚   β”œβ”€β”€ configuration/
β”‚   β”‚   └── app.py                # FastAPI app initialization
β”‚   β”œβ”€β”€ middlewares/              # HTTP middlewares
β”‚   β”‚   β”œβ”€β”€ __init__.py
β”‚   β”‚   └── database.py           # Database session middleware
β”‚   β”œβ”€β”€ routers/                  # API routers
β”‚   β”‚   β”œβ”€β”€ __init__.py           # Router registration
β”‚   β”‚   └── root/                 # Root endpoints
β”‚   β”‚       β”œβ”€β”€ router.py         # Route definitions
β”‚   β”‚       β”œβ”€β”€ actions.py        # Business logic
β”‚   β”‚       β”œβ”€β”€ dal.py            # Data access layer
β”‚   β”‚       β”œβ”€β”€ models.py         # Database models
β”‚   β”‚       └── schemas.py        # Request/response schemas
β”‚   β”œβ”€β”€ database/                 # Database configuration
β”‚   β”‚   β”œβ”€β”€ core.py               # Database engine and sessions
β”‚   β”‚   β”œβ”€β”€ base.py               # Base model class
β”‚   β”‚   β”œβ”€β”€ dependencies.py       # Database dependencies
β”‚   β”‚   β”œβ”€β”€ logging.py            # Session tracking
β”‚   β”‚   └── alembic/              # Database migrations
β”‚   β”œβ”€β”€ redis_client/             # Redis operations
β”‚   β”‚   └── redis.py              # Redis controller with caching methods
β”‚   β”œβ”€β”€ services/                 # External service integrations
β”‚   └── misc/                     # Utilities
β”‚       β”œβ”€β”€ security.py           # Security utilities
β”‚       └── timezone.py           # Timezone utilities
β”œβ”€β”€ docker/
β”‚   β”œβ”€β”€ Dockerfile                # Production Dockerfile
β”‚   β”œβ”€β”€ Dockerfile.dev            # Development Dockerfile
β”‚   β”œβ”€β”€ docker-compose.yml        # Production stack
β”‚   β”œβ”€β”€ docker-compose.dev.yml    # Development stack
β”‚   └── nginx/
β”‚       └── nginx.conf            # Nginx configuration
β”œβ”€β”€ daemon-service/
β”‚   └── fastapi-app.service       # Systemd service
β”œβ”€β”€ config.ini.example            # Configuration template
β”œβ”€β”€ alembic.ini.example           # Alembic configuration template
β”œβ”€β”€ requirements.txt              # Python dependencies
β”œβ”€β”€ Makefile                      # Build commands
β”œβ”€β”€ start.sh                      # Startup script
└── README.md                     # This file

Makefile Commands

make help           # Show all available commands
make install        # Install dependencies
make dev            # Start development environment
make build          # Build production Docker image
make up             # Start production environment
make down           # Stop all containers
make logs           # Show logs
make clean          # Remove containers and volumes
make test           # Run tests
make lint           # Run linter
make format         # Format code
make migrate        # Apply migrations
make migrate-create # Create new migration

CI/CD

GitHub Actions workflow automatically:

  1. Runs tests on every PR
  2. Checks code with linter
  3. Builds Docker image
  4. Deploys to production on push to main

Required GitHub Secrets:

  • SSH_PRIVATE_KEY - SSH key for server access
  • SSH_HOST - Server host
  • SSH_USER - Server user
  • CONFIG_INI - Contents of config.ini file for production
  • ALEMBIC_INI - Contents of alembic.ini file for production
  • DOCKER_USERNAME - Docker Hub username (optional)
  • DOCKER_PASSWORD - Docker Hub password (optional)

Configuration

Application uses INI files for configuration (see config.ini.example):

[POSTGRES]
# PostgreSQL database configuration
DATABASE = postgresql
DRIVER = asyncpg
DATABASE_NAME = your_database_name
USERNAME = postgres
PASSWORD = your_password
IP = localhost
PORT = 5432

# Connection pool settings
DATABASE_ENGINE_POOL_TIMEOUT = 30
DATABASE_ENGINE_POOL_RECYCLE = 3600
DATABASE_ENGINE_POOL_SIZE = 5
DATABASE_ENGINE_MAX_OVERFLOW = 10
DATABASE_ENGINE_POOL_PING = true

# Database echo (SQL logging) - set to false in production
DATABASE_ECHO = false

[UVICORN]
# Uvicorn server configuration
HOST = 0.0.0.0
PORT = 8000
WORKERS = 4
LOOP = uvloop          # Event loop: asyncio | uvloop (uvloop is faster)
HTTP = httptools       # HTTP protocol: h11 | httptools (httptools is faster)

[REDIS]
# Redis cache configuration
HOST = localhost
PORT = 6379
DB = 0
PASSWORD =

Key Features

Database Middleware

  • Automatic session management per request
  • Auto-commit on success, rollback on error
  • Session tracking for debugging
  • Request ID generation for tracing

Redis Client

  • Simple caching interface with get(), set(), delete(), update()
  • JSON serialization support with get_json() and set_json()
  • TTL (Time To Live) management
  • Multiple key deletion support

Health Check

  • Database connectivity check
  • Redis connectivity check
  • Returns 200 (healthy) or 503 (unhealthy)
  • Accessible at /api/root/health

Systemd Service

To run as systemd service:

  1. Copy service file:
sudo cp daemon-service/fastapi-app.service /etc/systemd/system/
  1. Edit paths in service file

  2. Start service:

sudo systemctl daemon-reload
sudo systemctl enable fastapi-app
sudo systemctl start fastapi-app

Testing

# Run all tests
make test

# Run with coverage
pytest --cov=app --cov-report=html

# Run specific test
pytest tests/test_api.py -v

Development

Creating new migration:

make migrate-create
# or
alembic revision --autogenerate -m "migration description"

Applying migrations:

make migrate
# or
alembic upgrade head

Code formatting:

make format

License

MIT License - see LICENSE file

About

No description, website, or topics provided.

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages