Skip to main content

A comprehensive toolkit for kickstarting FastAPI projects with best practices.

Project description

FastAPI Init Toolkit ๐Ÿš€

Python 3.8+ FastAPI License: MIT PyPI version

A comprehensive toolkit for kickstarting FastAPI projects with enterprise-grade features, best practices, and production-ready configurations.

โœจ Features

๐Ÿ—๏ธ Project Scaffolding

  • Best-practice project structure with organized folders and modules
  • Template-based generation with customizable components
  • Multiple project types (basic, with database, with auth, with Docker)
  • Automatic import management and dependency resolution

๐Ÿ” Authentication & Security

  • JWT-based authentication with configurable expiration
  • Password hashing with bcrypt
  • OAuth2 integration ready
  • Role-based access control (RBAC) support
  • CORS configuration with customizable origins

๐Ÿ—„๏ธ Database Integration

  • SQLAlchemy ORM with async support
  • Alembic migrations for database versioning
  • Multiple database support (SQLite, PostgreSQL, MySQL)
  • Database health checks and connection pooling
  • Model generation with relationships

๐Ÿงช Testing & Quality

  • Comprehensive test setup with pytest and pytest-asyncio
  • Test fixtures and utilities
  • Coverage reporting integration
  • Async test support for FastAPI endpoints
  • Mock utilities for external dependencies

๐Ÿณ Docker & Deployment

  • Multi-stage Dockerfile with security best practices
  • Docker Compose with database and app services
  • Health checks and graceful shutdown
  • Production-ready configurations
  • Environment variable management

๐Ÿ“Š Monitoring & Observability

  • Structured logging with configurable levels
  • Request/response monitoring with timing
  • Rate limiting middleware
  • Error tracking and reporting
  • Performance metrics collection

๐Ÿ”ง Development Tools

  • Code formatting with Black and isort
  • Linting with flake8
  • Type checking with mypy
  • Pre-commit hooks for code quality
  • Makefile with common development tasks

๐Ÿ“š Documentation

  • Automatic API documentation (Swagger/OpenAPI)
  • Project onboarding reports with route analysis
  • Environment health checks
  • Dependency analysis and recommendations

๐Ÿš€ Quick Start

Installation

# Install from PyPI
pip install fastapi-init

# Install with development dependencies
pip install fastapi-init[dev]

# Install with database support
pip install fastapi-init[database]

# Install with monitoring support
pip install fastapi-init[monitoring]

Create Your First Project

# Basic project
fastapi-init init my-api

# With database and authentication
fastapi-init init my-api --with-database --with-auth

# With Docker support
fastapi-init init my-api --with-docker --with-tests

# Full-featured project
fastapi-init init my-api --with-database --with-auth --with-docker --with-tests

Project Structure

my-api/
โ”œโ”€โ”€ app/
โ”‚   โ”œโ”€โ”€ api/
โ”‚   โ”‚   โ””โ”€โ”€ v1/
โ”‚   โ”‚       โ”œโ”€โ”€ auth_router.py      # Authentication endpoints
โ”‚   โ”‚       โ”œโ”€โ”€ health.py           # Health check endpoints
โ”‚   โ”‚       โ””โ”€โ”€ router.py           # Main API router
โ”‚   โ”œโ”€โ”€ core/
โ”‚   โ”‚   โ”œโ”€โ”€ auth.py                 # JWT authentication logic
โ”‚   โ”‚   โ”œโ”€โ”€ config.py               # Application settings
โ”‚   โ”‚   โ”œโ”€โ”€ database.py             # Database configuration
โ”‚   โ”‚   โ”œโ”€โ”€ logging.py              # Logging setup
โ”‚   โ”‚   โ””โ”€โ”€ middleware.py           # Custom middleware
โ”‚   โ”œโ”€โ”€ models/
โ”‚   โ”‚   โ””โ”€โ”€ models.py               # SQLAlchemy models
โ”‚   โ”œโ”€โ”€ schemas/
โ”‚   โ”‚   โ””โ”€โ”€ schemas.py              # Pydantic schemas
โ”‚   โ””โ”€โ”€ main.py                     # FastAPI application
โ”œโ”€โ”€ tests/
โ”‚   โ”œโ”€โ”€ api/
โ”‚   โ”œโ”€โ”€ core/
โ”‚   โ””โ”€โ”€ conftest.py                 # Test configuration
โ”œโ”€โ”€ alembic/                        # Database migrations
โ”œโ”€โ”€ logs/                           # Application logs
โ”œโ”€โ”€ requirements.txt                # Dependencies
โ”œโ”€โ”€ Dockerfile                      # Docker configuration
โ”œโ”€โ”€ docker-compose.yml              # Docker Compose
โ”œโ”€โ”€ .env.example                    # Environment variables
โ””โ”€โ”€ README.md                       # Project documentation

๐Ÿ“– Usage Guide

Basic Commands

# Initialize a new project
fastapi-init init my-project

# Check environment for issues
fastapi-init env-check

# Add error handling middleware
fastapi-init add-error-middleware

# Set up testing framework
fastapi-init test-init

# Generate onboarding report
fastapi-init onboarding-report

# Set up database migrations
fastapi-init setup-database

# Add Docker configuration
fastapi-init docker-setup

# Add monitoring and logging
fastapi-init add-monitoring

# Add rate limiting
fastapi-init add-rate-limiting

Advanced Usage

Database Setup

# Initialize with database support
fastapi-init init my-api --with-database

cd my-api

# Set up environment variables
cp .env.example .env
# Edit .env with your database configuration

# Run migrations
alembic upgrade head

Authentication Setup

# Initialize with authentication
fastapi-init init my-api --with-auth

# The project will include:
# - JWT token generation and validation
# - User registration and login endpoints
# - Password hashing with bcrypt
# - Protected route decorators

Docker Deployment

# Initialize with Docker support
fastapi-init init my-api --with-docker

# Build and run with Docker Compose
docker-compose up -d

# Or build manually
docker build -t my-api .
docker run -p 8000:8000 my-api

Configuration

Environment Variables

# Application Settings
APP_NAME=my-api
VERSION=1.0.0
DEBUG=True
HOST=0.0.0.0
PORT=8000

# Security
SECRET_KEY=your-super-secret-key-change-this-in-production
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30

# Database
DATABASE_URL=sqlite:///./app.db
# For PostgreSQL: postgresql://user:password@localhost/my-api

# CORS
ALLOWED_ORIGINS=["http://localhost:3000","http://localhost:8080"]

# Logging
LOG_LEVEL=INFO
LOG_FILE=app.log

# Rate Limiting
RATE_LIMIT_PER_MINUTE=60

Database Configuration

# app/core/config.py
class Settings(BaseSettings):
    database_url: str = "sqlite:///./app.db"
    
    # For PostgreSQL
    # database_url: str = "postgresql://user:password@localhost/my-api"
    
    # For MySQL
    # database_url: str = "mysql+pymysql://user:password@localhost/my-api"

๐Ÿงช Testing

Running Tests

# Run all tests
pytest

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

# Run specific test file
pytest tests/test_auth.py -v

# Run async tests
pytest tests/ -v --asyncio-mode=auto

Test Structure

# tests/test_auth.py
import pytest
from fastapi.testclient import TestClient
from app.main import app

client = TestClient(app)

def test_register_user():
    response = client.post("/api/v1/auth/register", json={
        "email": "test@example.com",
        "username": "testuser",
        "password": "testpass123"
    })
    assert response.status_code == 200
    assert "id" in response.json()

def test_login_user():
    response = client.post("/api/v1/auth/token", data={
        "username": "testuser",
        "password": "testpass123"
    })
    assert response.status_code == 200
    assert "access_token" in response.json()

๐Ÿณ Docker

Docker Commands

# Build image
docker build -t my-api .

# Run container
docker run -p 8000:8000 my-api

# Run with environment variables
docker run -p 8000:8000 -e DATABASE_URL=postgresql://... my-api

# Use Docker Compose
docker-compose up -d

Docker Compose Services

version: '3.8'

services:
  app:
    build: .
    ports:
      - "8000:8000"
    environment:
      - DATABASE_URL=postgresql://user:password@db:5432/my-api
      - SECRET_KEY=your-secret-key-here
    depends_on:
      - db
    volumes:
      - ./logs:/app/logs
    restart: unless-stopped

  db:
    image: postgres:15
    environment:
      - POSTGRES_DB=my-api
      - POSTGRES_USER=user
      - POSTGRES_PASSWORD=password
    volumes:
      - postgres_data:/var/lib/postgresql/data
    ports:
      - "5432:5432"
    restart: unless-stopped

volumes:
  postgres_data:

๐Ÿ”ง Development

Code Quality

# Format code
black app/ tests/

# Sort imports
isort app/ tests/

# Lint code
flake8 app/ tests/

# Type checking
mypy app/

# Run all quality checks
make format lint type-check

Pre-commit Hooks

# Install pre-commit hooks
pre-commit install

# Run hooks manually
pre-commit run --all-files

Makefile Commands

# Show all available commands
make help

# Install dependencies
make install

# Run tests
make test

# Run with coverage
make test-cov

# Start development server
make run

# Start production server
make run-prod

# Clean up generated files
make clean

# Build Docker image
make docker-build

# Run Docker container
make docker-run

๐Ÿ“Š Monitoring & Logging

Logging Configuration

# app/core/logging.py
import logging
import sys
from pathlib import Path

def setup_logging():
    log_dir = Path("logs")
    log_dir.mkdir(exist_ok=True)
    
    logging.basicConfig(
        level=logging.INFO,
        format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
        handlers=[
            logging.FileHandler("app.log"),
            logging.StreamHandler(sys.stdout)
        ]
    )

Health Checks

# app/api/v1/health.py
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from app.core.database import get_db

router = APIRouter()

@router.get("/")
async def health_check():
    return {"status": "healthy"}

@router.get("/db")
async def database_health_check(db: Session = Depends(get_db)):
    try:
        db.execute("SELECT 1")
        return {"status": "healthy", "database": "connected"}
    except Exception as e:
        return {"status": "unhealthy", "database": str(e)}

๐Ÿ”’ Security Features

JWT Authentication

# app/core/auth.py
from datetime import datetime, timedelta
from jose import JWTError, jwt
from passlib.context import CryptContext

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
    to_encode = data.copy()
    if expires_delta:
        expire = datetime.utcnow() + expires_delta
    else:
        expire = datetime.utcnow() + timedelta(minutes=15)
    to_encode.update({"exp": expire})
    encoded_jwt = jwt.encode(to_encode, settings.secret_key, algorithm=settings.algorithm)
    return encoded_jwt

Rate Limiting

# app/core/rate_limit.py
from fastapi import HTTPException, Request
from starlette.middleware.base import BaseHTTPMiddleware

class RateLimitMiddleware(BaseHTTPMiddleware):
    def __init__(self, app, requests_per_minute: int = 60):
        super().__init__(app)
        self.requests_per_minute = requests_per_minute
        self.requests = defaultdict(list)
    
    async def dispatch(self, request: Request, call_next):
        client_ip = request.client.host
        now = time.time()
        
        # Clean old requests
        self.requests[client_ip] = [
            req_time for req_time in self.requests[client_ip]
            if now - req_time < 60
        ]
        
        # Check rate limit
        if len(self.requests[client_ip]) >= self.requests_per_minute:
            raise HTTPException(
                status_code=429,
                detail="Rate limit exceeded. Please try again later."
            )
        
        # Add current request
        self.requests[client_ip].append(now)
        
        return await call_next(request)

๐Ÿ“š API Documentation

Automatic Documentation

Once your FastAPI application is running, you can access:

Example API Endpoints

# Authentication endpoints
POST /api/v1/auth/register     # Register new user
POST /api/v1/auth/token        # Login and get JWT token
GET  /api/v1/auth/me           # Get current user info

# Health check endpoints
GET  /api/v1/health/           # Basic health check
GET  /api/v1/health/db         # Database health check

# Root endpoint
GET  /                         # Welcome message and API info

๐Ÿค Contributing

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

Development Setup

# Clone the repository
git clone https://github.com/yourusername/fastapi-init.git
cd fastapi-init

# Install in development mode
pip install -e .[dev]

# Run tests
pytest

# Run linting
flake8 fastapi_init/ tests/

# Run type checking
mypy fastapi_init/

๐Ÿ“„ License

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

๐Ÿ™ Acknowledgments

  • FastAPI - The web framework for building APIs
  • SQLAlchemy - The database toolkit
  • Pydantic - Data validation using Python type annotations
  • Alembic - Database migration tool
  • Click - Command line interface creation kit

๐Ÿ“ž Support


Made with โค๏ธ for the FastAPI community

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fastapi_init_project-0.2.0.tar.gz (33.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fastapi_init_project-0.2.0-py3-none-any.whl (32.7 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_init_project-0.2.0.tar.gz.

File metadata

  • Download URL: fastapi_init_project-0.2.0.tar.gz
  • Upload date:
  • Size: 33.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.1

File hashes

Hashes for fastapi_init_project-0.2.0.tar.gz
Algorithm Hash digest
SHA256 897d77f83cf31235ee29029a872f625d39265c6fede6a8d5473f61169419b0b7
MD5 1cead54f629b93c29213529f8b4ffef9
BLAKE2b-256 9a83bfc967e52be8cc046f8647ae04ebddbae59bfced598a47741a71aa622324

See more details on using hashes here.

File details

Details for the file fastapi_init_project-0.2.0-py3-none-any.whl.

File metadata

File hashes

Hashes for fastapi_init_project-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 4bb2bdfc490118007477700cd374831eda2c51604bcb35002f9d5209752da8bf
MD5 1341641836883447bdc3cd1bf787bb07
BLAKE2b-256 9a781aff4432ab6c17f4dfd17262af3ca026cbb769865a8e743fd37ee156e9a6

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page