Skip to content

Introduction

Welcome to the FastAPI Backend Template documentation. This project is a production-ready foundation for scalable web applications leveraging FastAPI, SQLModel, and Alembic.

  • React Frontend Template: A companion frontend built with React, Vite, and Tailwind CSS.
  • Expo Mobile App Template: A companion mobile client built with Expo.

🌟 Key Features

  • Python 3.12+ Runtime: Leverages the latest interpreter performance enhancements.
  • Modular Architecture: Clean separation of API, Services, CRUD, and Models.
  • Authentication: OAuth2 password flow with Argon2 password hashing, typed JWT access and refresh tokens, and revocation.
  • Authorization: Granular RBAC (Super User, Admin, User) with one policy module for user management.
  • Account Security: Lockout, password history and single-use password reset, rate limits and security headers.
  • Consistent Errors: RFC 9457 Problem Details for every error.
  • Application Features: ToDo lists, a per-request audit trail, system error logs and role-specific dashboards.
  • Observability: Structured JSON logging with request IDs, Prometheus metrics, health probes, and opt-in OpenTelemetry tracing and Sentry.
  • Contract-First Workflow: Committed OpenAPI schema with drift detection in CI.
  • Local Reverse Proxy: Traefik routes local services through stable .test domains.
  • Email Testing: Integrated Mailpit for capturing and inspecting outgoing emails locally.
  • Automated Quality: Fast linting, formatting, and type-checking powered by Ruff, Mypy, and Prek.
  • AWS Free-Tier Deployment (optional): Lambda, CloudFront, S3 and SQS with Neon for PostgreSQL. See Deployment.
  • Modern Tooling: Powered by uv for dependency management.
  • AI-Assisted Development: One rule set (AGENTS.md) for all AI coding assistants.

📁 Project Structure

fastapi-backend-template/
├── .github/                       # CI workflows, Dependabot, issue and PR templates
├── .vscode/                       # Debug configuration (launch.json)
├── alembic/                       # Migration environment; scripts in versions/
├── app/                           # Main application logic
│   ├── api/                       # API entry points: auth/RBAC deps.py, health.py
│   │   └── v1/                    # API versioning
│   │       ├── endpoints/         # Route handlers: login, users, todos, activities, dashboards
│   │       └── router.py          # Main router merging all v1 endpoints
│   ├── aws/                       # Lambda worker: queued emails and the audit purge
│   ├── core/                      # Config, security (JWT), rate limiting, errors, email, logging, telemetry
│   ├── crud/                      # Atomic DB operations (todo.py also filters ToDo visibility, ADR 0004)
│   ├── db/                        # Engine/session, seed data, retention job
│   ├── email-templates/           # MJML sources (src/) and compiled HTML (build/)
│   ├── middleware/                # Request context, activity log; CloudFront origin check and response hold (AWS)
│   ├── models/                    # SQLModel tables and DTOs (data transfer objects)
│   ├── services/                  # Business logic and RBAC policy (auth, users, dashboards)
│   └── main.py                    # FastAPI application initialization
├── docs/                          # Zensical documentation source (Markdown)
├── infra/aws/                     # Terraform for the AWS free-tier deployment
├── scripts/                       # Prestart job, email template build, OpenAPI export, Lambda package
├── tests/                         # Pytest suite: api/, aws/, core/, db/, middleware/
├── traefik/                       # Traefik file-provider route configuration
│
│   # Project docs
├── README.md                      # Project overview and quick start
├── CONTRIBUTING.md                # Contribution guidelines
├── SECURITY.md                    # Security policy
├── LICENSE                        # License terms
├── release-notes.md               # Change history
├── AGENTS.md                      # Rules for AI coding assistants
├── GEMINI.md                      # Gemini CLI context; imports AGENTS.md
│
│   # Configuration
├── .env.example                   # Template for environment variables
├── .pre-commit-config.yaml        # Prek/pre-commit hook configuration
├── alembic.ini                    # Alembic configuration
├── openapi.json                   # Committed API contract
├── zensical.toml                  # Zensical documentation configuration
│
│   # Docker
├── Dockerfile                     # Multi-stage, non-root production build
├── docker-compose.yaml            # Production-shaped base stack
├── docker-compose.override.yml    # Dev overrides: hot reload, pgAdmin, Mailpit, local Traefik
├── docker-compose.ci.yml          # Runs the test suite inside the image (CI)
│
│   # Dependencies
├── .python-version                # Python version used by uv
├── pyproject.toml                 # Project metadata and dependencies (uv)
└── uv.lock                        # Deterministic dependency lock file

🤖 AI-Driven Development

The repository ships an AGENTS.md with the architectural rules for AI coding assistants (Gemini CLI, Google Antigravity, Claude Code and others), so AI-made changes follow the same standards as human ones.

🚀 Quick Start

1. Prerequisites

Ensure you have the following installed: - Python 3.12+ - uv: curl -LsSf https://astral.sh/uv/install.sh | sh - Docker & Docker Compose

2. Setup

# Clone the repository
git clone git@github.com:mobitrendz/fastapi-backend-template.git
cd fastapi-backend-template

# Sync dependencies
uv sync

# Install Prek hooks
uv run prek install

# Activate virtual environment
source .venv/bin/activate

# Create .env from example
cp .env.example .env

Before starting the stack, replace the changethis values in .env. See Environment Configuration.

3. Run with Docker

# Deploy local development stack
docker compose up --build
This automatically runs migrations and seeds the initial data via the prestart service.

Access the API at http://localhost:8000/docs or, after adding the local hosts entries, at http://api.fastapi-template.test/docs.

4. Quality Assurance

Ensure the system is stable by running the test suite:

# Run all tests
uv run pytest

# Run tests with coverage report
uv run pytest --cov=app --cov-report=term-missing

📚 Documentation Sections

🚀 Release Checklist for Developers

Before merging changes to master, ensure you have completed this checklist:

  1. Quality Hooks: Run uv run prek run --all-files (Ruff, Mypy, Bandit, lockfile, docs build).
  2. Tests & Coverage: Run uv run pytest. Coverage must remain at or above 90%.
  3. Migrations: Add an Alembic migration for any model change; uv run alembic check must pass.
  4. Contract Integrity: Run uv run python scripts/export-openapi.py openapi.json and commit any schema changes. This keeps the frontend in sync.
  5. Documentation: Update the Zensical documentation and release-notes.md for new features or breaking changes.