EF

eslam5464/fastapi-template

Developer tools
71ย stars Quality 70 Trend 70

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

Overview

A production-ready FastAPI project template with modern best practices, async support, JWT authentication, and PostgreSQL integration. - - Modern, fast web framework for building APIs, with versioned routers (/v1, /v2) - - Async database integration with SQLAlchemy 2.0 and Alembic migrations - - Secure token-based authentication with token blacklisting - - Repository pattern, dependency injection, and enforced module boundaries (tach) - - CSRF, rate limiting, and security headers middleware - - Backend, Postgres, and Redis ready to run - - 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 .

README

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, 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 
    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 copier copy gh:eslam5464/Fastapi-Template  --trust

Alternative: if youโ€™d rather have copier installed permanently (e.g. for copier update later), use uv tool install copier 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 substitutes your answers into the copied files, 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 entirely in copier.yml and scripts/generate/post_gen.py, which run after copying and edit the same real files you already build, test, and run directly. There are no separate .jinja template files to keep in sync.

๐Ÿค– AI Coding Assistant Support

This repo packages its whole architecture โ€” layering rules, SQLAlchemy patterns, auth/ security conventions, testing gotchas, CI/tooling config, and the Copier generation mechanics above โ€” as something an AI coding assistant can actually use, not just read about. It has two jobs, for whichever assistant you use:

  • Scaffold a brand-new project with this architecture by driving the real Copier template (not re-typing boilerplate from memory, so it canโ€™t drift from whatโ€™s actually here).
  • Extend or review an existing instance of this architecture โ€” this repo, or any project generated from it โ€” adding new endpoints/services/models consistently with whatโ€™s already there, or auditing a diff/codebase against the documented rules and anti-patterns catalog before you merge it. Reviews always list whatโ€™s wrong and why, and whatโ€™s suggested instead, and leave applying any fix up to you.

Install it in another project โ€” one command, any of 76+ agents

The canonical source lives at .claude/skills/fastapi-template-architect/ in Agent Skills format (portable โ€” not Claude-specific). To pull it into an unrelated project for Claude Code, Codex CLI, GitHub Copilot, Cursor, Windsurf, or any other agent supported by skills (vercel-labs/skills), run this from that project:

npx skills add eslam5464/Fastapi-Template --skill fastapi-template-architect

Add -g to install it once to your personal/global skills folder instead of just this project, or -a claude-code / -a codex to target one agent specifically. This is a real, general-purpose skill installer, not something built for this repo โ€” it works the same way for anyone elseโ€™s skills too.

GitHub Copilot support in that CLI is unverified as of this writing โ€” Copilotโ€™s own docs donโ€™t describe a native skills-folder mechanism yet. If -a github-copilot doesnโ€™t do anything for you, use the Copilot-specific files below instead.

Working in this repo, or in a project generated from it? Nothing to do

Each of these is auto-discovered with zero install step, for the same reason: every project generated from this template inherits them automatically, just like the rest of the architecture.

Fallback: manual copy/symlink (if youโ€™d rather not run npx)

# macOS/Linux
cp -r .claude/skills/fastapi-template-architect ~/.claude/skills/
# Windows (PowerShell) - a junction instead of a copy keeps it in sync automatically
New-Item -ItemType Junction -Path "$env:USERPROFILE\.claude\skills\fastapi-template-architect" -Target "$PWD\.claude\skills\fastapi-template-architect"

See the skillโ€™s own SKILL.md for the full detail on both modes.

๐Ÿ“– Documentation

Detailed documentation is available in the docs/ folder:

๐Ÿ›๏ธ Architecture

Screenshot of the interactive diagram โ€” client โ†’ API Gateway โ†’ versioned API โ†’ Service Layer โ†’ Repository/ORM โ†’ PostgreSQL, with Redis-backed caching/rate-limiting/token-blacklisting and an optional Celery worker for background jobs, all inside the Docker Compose trusted network.

See Architecture Overview for the full write-up. The interactive version lives at docs/architecture/fastapi-template.architecture.html โ€” download it and open it locally for guided views, theme toggling, and per-node source links (GitHub renders .html files as source, not a live page, so the link above wonโ€™t run it in-browser).

๐Ÿ—๏ธ 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

View this README on GitHub

Recommended Tools

Try a different keyword or remove a filter.

Install

npx skillfish add eslam5464/fastapi-template