A comprehensive toolkit for kickstarting FastAPI projects with best practices.
Project description
FastAPI Init Toolkit ๐
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:
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
- OpenAPI JSON: http://localhost:8000/openapi.json
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
- ๐ง Email: your.email@example.com
- ๐ Issues: GitHub Issues
- ๐ Documentation: GitHub Wiki
- ๐ฌ Discussions: GitHub Discussions
Made with โค๏ธ for the FastAPI community
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file fastapi_init_project-0.2.1.tar.gz.
File metadata
- Download URL: fastapi_init_project-0.2.1.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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
5cbd5c1a70f17d3239abc2ac718a5e86b897dd54186f41873aacdc280bdbb2c9
|
|
| MD5 |
00fb1950a87c31d2a2c87f830eaf23e2
|
|
| BLAKE2b-256 |
bfbe64ff3fddc7efded16aa2ec0861cfae5472f14a53bc1a4348ac1fe4cdf5ca
|
File details
Details for the file fastapi_init_project-0.2.1-py3-none-any.whl.
File metadata
- Download URL: fastapi_init_project-0.2.1-py3-none-any.whl
- Upload date:
- Size: 32.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.1
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
2f76c4304a8f71f90417bf913e3aab61727eb4d9f742d0b2175bfcf1bcd6e363
|
|
| MD5 |
18996d982cc689f8f570dc40699b61f9
|
|
| BLAKE2b-256 |
88bb6fffbbdcb26da55e28483bb608d175c711197395d31812f19e0dec7174cf
|