Skip to content
Public template

About

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

Topics

Resources

Security policy

Stars

71 stars

Watchers

2 watching

Forks

Latest commit

Β 

History

227 Commits

Folders and files

Repository files navigation

FastAPI Template

CI

CodeQL

Coverage License: MIT

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

✨ Features

  • πŸš€ FastAPI - Modern, fast web framework for building APIs, with versioned routers (one mounted app per API version, starting at /v1)
  • πŸ“Š PostgreSQL - Async database integration with SQLAlchemy 2.0 and Alembic migrations
  • πŸ” JWT Authentication - Secure token-based authentication
  • 🚫 Token revocation - logout puts the token on a Redis blacklist
  • ⚠️ Logout does not revoke tokens - without the token blacklist, a logged-out access token stays valid until it expires; keep expiry times short
  • ⚠️ No authentication - every route is public until you add your own login and access checks
  • πŸ—οΈ Clean Architecture - Repository pattern, dependency injection, and enforced module boundaries (tach)
  • πŸ“¦ Example CRUD domain - Items: a model, repository, service, /v1/items endpoints, migration and tests to copy from
  • πŸ”’ Security headers - OWASP-recommended security headers on every response
  • πŸ”’ Security - Trusted hosts and a CORS allowlist
  • πŸ›‘οΈ CSRF protection - Double-submit cookie middleware for browser clients
  • 🚦 Rate limiting - Redis sliding-window limits as FastAPI dependencies
  • 🐳 Docker Compose - Backend and Postgres ready to run
  • πŸ§ͺ CI & Testing - Pytest with coverage gating, plus lint/type/security checks in GitHub Actions

Plus optional integrations:

  • caching
  • background jobs
  • cloud storage
  • Firebase
  • Apple Pay
  • 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 (the services chosen at generation are regular 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/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 <new-project-dir> --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 how much of the template to include. The services question offers three values: minimal (the base, pre-selected in an interactive run), custom (choose optional services one by one), or full (everything). copier copy ... --defaults selects full, so it generates the project with every optional service; for a scripted minimal base use copier copy ... --defaults --data services=minimal. The optional services are authentication, the example Items domain, the /v2 API scaffold, the CSRF middleware, the security headers middleware, the Redis cache, rate limiting, the token blacklist, Celery, Firebase, Firestore, Google Cloud Storage, BackBlaze B2, Resend, Brevo, OpenObserve, Apple Pay, the Alembic helper scripts, the GitHub extras (CodeQL, Dependabot, issue and pull request templates, CODEOWNERS, SECURITY.md) and the extra documentation (guides, architecture, API reference, runbooks, strategy). 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.

A skill installed this way (or copied, below) carries reference copies of key template files in its assets/ folder, shown with every optional service included. In a project generated from this template, those copies match the services that project has.

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:

  • LLM Index - Canonical documentation entrypoint for AI and quick doc navigation
  • AI Coding Assistant Skill - Scaffold or extend/review projects with this architecture from Claude Code, Codex CLI, or GitHub Copilot
  • Features - Full list of integrations and services, with setup notes

πŸ›οΈ Architecture

See Architecture Overview for the layers, request flow and module boundaries.

FastAPI Template runtime architecture diagram: client through the API gateway, versioned routers, service layer, repository/ORM, PostgreSQL, Redis-backed caching and rate limiting, and an optional Celery worker, all inside a Docker Compose trusted network.

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.

The interactive version of this diagram 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/       # Route dependencies
β”‚   β”œβ”€β”€ core/               # Core functionality
β”‚   β”‚   β”œβ”€β”€ config.py       # Configuration management
β”‚   β”‚   β”œβ”€β”€ db.py           # Database connection
β”‚   β”‚   └── exceptions/     # 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

JWT authentication with a User model: signup, login, access and refresh tokens, Argon2 password hashing, and a get_current_user dependency for protected routes. See docs/integrations/auth.md for the endpoints, the settings and how to protect a route.

πŸ› οΈ 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 the API, 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

Celery workers, the beat scheduler and the sample tasks: see docs/integrations/celery.md.

Database Migrations

Use the helper scripts (Recommended):

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

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

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

# Server
BACKEND_HOST=localhost
BACKEND_PORT=8799
CURRENT_ENVIRONMENT=local

Authentication:

SECRET_KEY=your-secret-key
ACCESS_TOKEN_EXPIRE_SECONDS=3600
REFRESH_TOKEN_EXPIRE_SECONDS=2592000

Redis (shared by the Redis-backed services this project uses):

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 user seeding:

ENABLE_DATA_SEEDING=false
SEEDING_USER_COUNT=100

Resend:

RESEND_API_KEY=your_resend_api_key_here

Brevo:

BREVO_API_KEY=your_brevo_api_key_here

.env.example lists every variable this project uses.

πŸ“¦ Dependencies

Core dependencies (FastAPI, SQLAlchemy, Alembic, Pydantic, Uvicorn) are always installed. The packages of the optional services chosen when the project was generated are regular dependencies too, so uv sync installs everything the project uses.

See docs/features.md for what each service 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

71 stars

Watchers

2 watching

Forks

Releases

Contributors

Languages