Skip to content

eslam5464/Fastapi-Template

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

146 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

FastAPI Template

CI CodeQL Coverage License: MIT

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, with versioned routers (/v1, /v2)
  • πŸ“Š PostgreSQL - Async database integration with SQLAlchemy 2.0 and Alembic migrations
  • πŸ” JWT Authentication - Secure token-based authentication with token blacklisting
  • πŸ—οΈ Clean Architecture - Repository pattern, dependency injection, and enforced module boundaries (tach)
  • πŸ”’ Security - CSRF, rate limiting, and security headers middleware
  • 🐳 Docker Compose - Backend, Postgres, and Redis ready to run
  • πŸ§ͺ CI & Testing - Pytest with coverage gating, plus lint/type/security checks in GitHub Actions

Plus optional integrations for caching, background jobs, cloud storage, Firebase, Apple Pay, and email delivery. For the full list of integrations and services, see docs/features.md.

πŸš€ 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 optional integrations as needed
    uv sync --all-groups --all-extras
    
    # Install pre-commit hooks
    pre-commit install

    Note: If you are facing SSL issues on Windows, use:

    uv sync --all-groups --native-tls
    uv sync --native-tls --all-extras
  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/v1/docs
  • http://localhost:8799/v2/docs

🧬 Using This as a Template

This repository doubles as a Copier template β€” generate a brand-new FastAPI project from it, with your own name, author info, and settings, without cloning and hand-editing:

# Run copier directly with uvx - no install/PATH setup needed
uvx --with jinja2-time copier copy gh:eslam5464/Fastapi-Template <new-project-dir> --trust

Note: --with jinja2-time is required because this template uses a Jinja extension (for the LICENSE copyright year) that isn't one of copier's own dependencies β€” without it you'll see Copier could not load some Jinja extensions: No module named 'jinja2_time'. uvx/uv tool run installs it alongside copier for this one run only.

Alternative: if you'd rather have copier installed permanently (e.g. for copier update later), use uv tool install copier --with jinja2-time instead. On Windows, that installs into a user tools directory that's often not yet on PATH in your current terminal session β€” if you see 'copier' is not recognized as an internal or external command right after installing, either open a new terminal window, or run uv tool update-shell and then restart the terminal. The uvx command above sidesteps the PATH issue entirely since it doesn't need copier installed anywhere persistent.

You'll be prompted for a project name, description, author name/email, GitHub username, Python version, and whether to include Apple Pay support. Everything identity-specific β€” the pyproject.toml name, Docker container names, the Postgres schema, README.md, LICENSE, CODEOWNERS β€” is filled in automatically; see docs/features.md for what ships by default versus what's opt-in.

--trust is required because generation runs a small post-processing script (scripts/generate/post_gen.py) that removes unused Apple Pay files when you opt out, regenerates uv.lock, and runs git init for you.

This repo itself stays fully runnable the whole time β€” the template mechanics live alongside the real code as .jinja-suffixed files (pyproject.toml.jinja, docker-compose.yml.jinja, etc.) plus copier.yml, none of which change how you build, test, or run this repo directly.

πŸ“– 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)
β”‚   β”‚   └── v2/             # API version 2
β”‚   β”œβ”€β”€ 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 Argon2 (via pwdlib)
  • Token blacklisting for secure logout
  • 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

Coverage Scope:

  • βœ… Unit, service, and integration tests
  • πŸ“Š Terminal and HTML coverage reports
  • 🎯 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
POSTGRES_HOST=localhost
POSTGRES_PORT=5432
POSTGRES_USER=postgres
POSTGRES_PASSWORD=your-postgres-password
POSTGRES_DB=postgres
POSTGRES_DB_SCHEMA=fastapi_template

# Security
SECRET_KEY=your-secret-key
ACCESS_TOKEN_EXPIRE_SECONDS=2582000
REFRESH_TOKEN_EXPIRE_SECONDS=2592000

# Server
BACKEND_HOST=localhost
BACKEND_PORT=8799
CURRENT_ENVIRONMENT=local

# 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

# Email Providers
resend_api_key=your_resend_api_key_here
brevo_api_key=your_brevo_api_key_here

πŸ“¦ Dependencies

Core dependencies (FastAPI, SQLAlchemy, Alembic, Pydantic, Uvicorn) are always installed. Optional integrations (Redis, Celery, Firebase, GCS, BackBlaze, Apple Pay, email providers) are opt-in extras β€” install only what you need:

uv sync --extra email
uv sync --extra cloud-service
uv sync --extra cache
uv sync --extra task-queue
uv sync --extra apple-services

See docs/features.md for what each extra provides and how to configure it.

🀝 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

Security policy

Stars

Watchers

Forks

Releases

Contributors

Languages