A production-ready FastAPI project template with modern best practices, async support, JWT authentication, and PostgreSQL integration.
- π FastAPI - Modern, fast web framework for building APIs
- π JWT Authentication - Secure token-based authentication system
- π PostgreSQL - Async database integration with SQLAlchemy 2.0
- ποΈ Database Migrations - Alembic for schema management
- ποΈ Clean Architecture - Repository pattern and dependency injection
- π Automatic API Documentation - Interactive Swagger UI and ReDoc
- π Security - Password hashing, CORS, and security middleware
- π Logging - Structured logging with Loguru
- β‘ Environment Management - Multi-environment configuration
- π§ͺ Development Tools - Pre-commit hooks, code formatting with Black
- βοΈ Cloud Storage Integration - BackBlaze B2 cloud storage service support
- π₯ Firebase Integration - Authentication, push notifications, and Firestore database
- β‘ Redis Caching - High-performance caching with shared connection pooling
- π¦ Rate Limiting - Sliding window rate limiting with microsecond precision
- π©οΈ Google Cloud Storage - GCS bucket integration for file management
- π§ͺ Comprehensive Testing - ~90% test coverage with 510+ passing tests
- βοΈ Background Jobs - Celery with Redis for async task processing and scheduled jobs
-
Clone the repository
git clone <your-repo-url> cd FastApi-Template
-
Install dependencies
Create a virtual environment
python -m venv .venv
Activate the virtual environment
# On Linux / macOS source .venv/bin/activate # On Windows (PowerShell) .venv\Scripts\Activate.ps1
Install dependencies
# Install dependencies uv sync --all-groups # Install pre-commit hooks pre-commit install
Note: If you are facing SSL issues on Windows, use:
uv sync --all-groups --native-tls
-
Set up environment variables
cp .env.example .env # Edit .env with your configuration -
Configure database
# Create database createdb fastapi_template # Run migrations alembic upgrade head
-
Start the development server
python main.py
The API will be available at http://localhost:8799 with interactive documentation at http://localhost:8799/docs.
Detailed documentation is available in the docs/ folder:
- Architecture - Project structure and design patterns
- API Reference - Endpoint documentation and examples
- Development Guide - Setup, testing, and contribution guidelines
- Deployment - Production deployment strategies
βββ app/
β βββ api/ # API routes and endpoints
β β βββ v1/ # API version 1
β β βββ endpoints/ # Individual endpoint modules
β β βββ deps/ # Dependencies (auth, database)
β βββ core/ # Core functionality
β β βββ auth.py # Authentication utilities
β β βββ config.py # Configuration management
β β βββ db.py # Database connection
β β βββ exceptions.py # Custom exceptions
β βββ models/ # SQLAlchemy models
β βββ schemas/ # Pydantic schemas
β βββ repos/ # Repository pattern implementations
β βββ services/ # Business logic and external services
β βββ middleware/ # Custom middleware
β βββ alembic/ # Database migrations
βββ docs/ # Detailed documentation
βββ scripts/ # Utility scripts
βββ logs/ # Application logs (Generated at runtime)
The template includes a complete JWT-based authentication system:
- User registration and login
- Access and refresh tokens
- Password hashing with bcrypt
- Protected routes with dependency injection
from app.api.v1.deps.auth import get_current_user
@router.get("/protected")
async def protected_route(current_user: User = Depends(get_current_user)):
return {"message": f"Hello {current_user.username}!"}The project includes several tools for maintaining code quality:
- Black - Code formatting
- Pre-commit hooks - Automated checks before commits
- Loguru - Structured logging
- Environment validation - Pydantic settings
The project maintains comprehensive test coverage with ~90% code coverage across all modules:
# Run all tests with verbose output and detailed reporting
uv run pytest -v
# Run tests with coverage report
uv run pytest tests/ --cov=app --cov-report=term --cov-report=html
# View detailed HTML coverage report
# Open htmlcov/index.html in your browserTest Statistics:
- β 510+ passing tests
- π ~90% code coverage
- π― Tests cover: API endpoints, authentication, database operations, services, middleware, and utilities
Run security analysis using Bandit:
uv run bandit -r app -f json -o bandit_results.jsonuv run pytest -vThe project uses Celery for background job processing with Redis as the message broker.
# Linux/macOS
./scripts/celery_worker.sh
# Windows
.\scripts\celery_worker.bat
# Or directly
celery -A app.services.task_queue worker --loglevel=info --pool=solo# Linux/macOS
./scripts/celery_beat.sh
# Windows
.\scripts\celery_beat.bat
# Or directly
celery -A app.services.task_queue beat --loglevel=infoAvailable Tasks:
seed_fake_users- Generates fake users for testing (runs every 10 seconds whenENABLE_DATA_SEEDING=true)
Use the scripts provided (Recommended):
# Run database migrations for linux/macOS
./scripts/alembic.sh
# Run database migrations for windows
.\scripts\alembic.batOr use Alembic commands directly:
# Create a new migration
alembic revision --autogenerate -m "Description"
# Apply migrations
alembic upgrade head
# Rollback migrations
alembic downgrade -1The application supports multiple environments:
- local - Development with debug features
- dev - Development server
- stg - Pre-production testing (Staging)
- prd - Production deployment
Configure via environment variables or .env file:
# Database
DATABASE_URL=postgresql+asyncpg://user:password@localhost/dbname
# Security
SECRET_KEY=your-secret-key
ACCESS_TOKEN_EXPIRE_MINUTES=30
# Server
BACKEND_HOST=0.0.0.0
BACKEND_PORT=8799
# Redis (for caching and rate limiting)
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASS=your-redis-password
# Rate Limiting
RATE_LIMIT_ENABLED=true
RATE_LIMIT_DEFAULT=100
RATE_LIMIT_WINDOW=60
# Celery & Background Tasks
ENABLE_DATA_SEEDING=false
SEEDING_USER_COUNT=100Key dependencies include:
- FastAPI - Web framework
- SQLAlchemy - ORM with async support
- Alembic - Database migrations
- Pydantic - Data validation
- Uvicorn - ASGI server
- PostgreSQL - Database driver (asyncpg)
- JWT - Token authentication
- Loguru - Logging
- Redis - Caching and rate limiting backend
- Celery - Distributed task queue for background jobs
- B2SDK - BackBlaze B2 cloud storage integration
- Firebase Admin - Firebase authentication and messaging
- Google Cloud Storage - GCS integration
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
- FastAPI - The amazing web framework
- SQLAlchemy - The Python SQL toolkit
- Pydantic - Data validation library
- Fastapi Template by tiangolo - A FastAPI project template
- Fastapi best practices - Inspiration for best practices
- Fastapi Tips - Useful tips and tricks from FastAPI Expert
- Fastapi structure - Project structure inspiration