Skip to content
/ Fastapi-Template Public template

πŸš€ Production-ready FastAPI template with JWT authentication, PostgreSQL integration, async support, clean architecture, and modern development tools.

License

Notifications You must be signed in to change notification settings

eslam5464/Fastapi-Template

Repository files navigation

FastAPI Template

A production-ready FastAPI project template with modern best practices, async support, JWT authentication, and PostgreSQL integration.

✨ Features

  • πŸš€ 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

πŸš€ Quick Start

Prerequisites

Installation

  1. Clone the repository

    git clone <your-repo-url>
    cd FastApi-Template
  2. 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
  3. Set up environment variables

    cp .env.example .env
    # Edit .env with your configuration
  4. Configure database

       # Create database
       createdb fastapi_template
    
       # Run migrations
       alembic upgrade head
  5. Start the development server

       python main.py

The API will be available at http://localhost:8799 with interactive documentation at http://localhost:8799/docs.

πŸ“– Documentation

Detailed documentation is available in the docs/ folder:

πŸ—οΈ Project Structure

β”œβ”€β”€ 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)

πŸ” Authentication

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

Example Usage

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}!"}

πŸ› οΈ Development

Code Quality

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

Testing

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 browser

Test Statistics:

  • βœ… 510+ passing tests
  • πŸ“Š ~90% code coverage
  • 🎯 Tests cover: API endpoints, authentication, database operations, services, middleware, and utilities

Security Analysis

Run security analysis using Bandit:

uv run bandit -r app -f json -o bandit_results.json

Running Tests

uv run pytest -v

Background Jobs & Task Queue

The project uses Celery for background job processing with Redis as the message broker.

Start Celery Worker

# Linux/macOS
./scripts/celery_worker.sh

# Windows
.\scripts\celery_worker.bat

# Or directly
celery -A app.services.task_queue worker --loglevel=info --pool=solo

Start Celery Beat (Scheduler)

# Linux/macOS
./scripts/celery_beat.sh

# Windows
.\scripts\celery_beat.bat

# Or directly
celery -A app.services.task_queue beat --loglevel=info

Available Tasks:

  • seed_fake_users - Generates fake users for testing (runs every 10 seconds when ENABLE_DATA_SEEDING=true)

Database Migrations

Use the scripts provided (Recommended):

# Run database migrations for linux/macOS
./scripts/alembic.sh

# Run database migrations for windows
.\scripts\alembic.bat

Or use Alembic commands directly:

# Create a new migration
alembic revision --autogenerate -m "Description"

# Apply migrations
alembic upgrade head

# Rollback migrations
alembic downgrade -1

🌍 Environment Configuration

The 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=100

πŸ“¦ Dependencies

Key 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

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

πŸ“„ License

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

πŸ™ Acknowledgments

About

πŸš€ Production-ready FastAPI template with JWT authentication, PostgreSQL integration, async support, clean architecture, and modern development tools.

Topics

Resources

License

Stars

Watchers

Forks

Languages