Skip to content

Development Guide

This guide covers everything you need to know to develop, test, and contribute to the FastAPI Backend Template.

๐Ÿ› ๏ธ Local Environment Setup

1. Install uv

This project uses uv for lightning-fast dependency management.

curl -LsSf https://astral.sh/uv/install.sh | sh

2. Install Docker & Docker Compose

Used for full-stack orchestration and environmental parity. - Install Docker Desktop

3. Sync & Setup Environment

# Sync dependencies
uv sync

# Install Prek hooks
uv run prek install

# Activate virtual environment
source .venv/bin/activate

โš™๏ธ Environment Configuration

To set up your local environment, copy the example configuration file:

cp .env.example .env

Every variable is documented inline in .env.example. The most important groups:

Group Key variables
Project ENVIRONMENT (local, ci, staging, production), PROJECT_NAME, STACK_NAME, DOMAIN, FRONTEND_HOST
HTTP API_V1_STR, BACKEND_CORS_ORIGINS, ALLOWED_HOSTS
AWS only DEFER_RESPONSE_UNTIL_COMPLETE, ORIGIN_VERIFY_SECRET (leave off locally)
Auth SECRET_KEY (openssl rand -hex 32), ACCESS_TOKEN_EXPIRE_MINUTES, REFRESH_TOKEN_EXPIRE_DAYS, EMAIL_RESET_TOKEN_EXPIRE_HOURS, ALGORITHM, JWT_ISSUER, JWT_AUDIENCE, MAX_FAILED_LOGIN_ATTEMPTS, ACCOUNT_LOCKOUT_MINUTES, PASSWORD_HISTORY_DEPTH
Super user SUPER_USER_NAME, SUPER_USER_EMAIL, SUPER_USER_PASSWORD
Database POSTGRES_*, DB_POOL_SIZE, DB_MAX_OVERFLOW, DB_POOL_RECYCLE_SECONDS, DB_STATEMENT_TIMEOUT_MS
pgAdmin (local only) PGADMIN_EMAIL, PGADMIN_PASSWORD
Email SMTP_*, EMAILS_FROM_EMAIL, EMAILS_FROM_NAME, EMAIL_QUEUE_URL (AWS only)
Rate limiting RATE_LIMIT_ENABLED, RATE_LIMIT_STORAGE_URI
Observability LOG_LEVEL, SENTRY_DSN, SENTRY_TRACES_SAMPLE_RATE, OTEL_EXPORTER_OTLP_ENDPOINT, OTEL_SERVICE_NAME, METRICS_ENABLED, AUDIT_RETENTION_DAYS

Secrets are validated

With ENVIRONMENT=staging or production the app refuses to start if SECRET_KEY, POSTGRES_PASSWORD or SUPER_USER_PASSWORD still hold a placeholder such as changethis, or if SECRET_KEY is shorter than 32 characters. In local and ci it only warns.

๐ŸŽจ Frontend Integration (Optional)

This backend is designed to work seamlessly with the React Frontend Template.

If you are developing both the frontend and backend locally: 1. Clone the frontend: git clone https://github.com/mobitrendz/react-frontend-template 2. CORS: Ensure BACKEND_CORS_ORIGINS in your .env includes the frontend's local address (usually http://localhost:5173). 3. Frontend Host: Update FRONTEND_HOST in your .env to match the frontend URL. This is used for generating links in system emails (e.g., password resets).


๐Ÿš€ Running the API Locally

Start Native Development Server (Hybrid Setup)

For developers who prefer running the database services via Docker while developing the FastAPI application natively on their host machine for faster iteration:

  1. Start Database Services only:

    docker compose up -d db pgadmin mailpit
    

  2. Configure Local Environment: Keep POSTGRES_SERVER=localhost and SMTP_HOST=localhost in .env (the defaults in .env.example).

  3. Run API Natively:

    uv sync                            # app + dev dependencies into .venv
    uv run alembic upgrade head        # apply migrations
    uv run fastapi dev --host 0.0.0.0  # hot reload on :8000
    
    With ENVIRONMENT=local the SUPER user is seeded automatically on startup. The API will be available at:

  4. API Documentation: http://localhost:8000/docs
  5. pgAdmin: http://localhost:5050
  6. Mailpit UI: http://localhost:8025
  7. Prometheus Metrics: http://localhost:8000/metrics
  8. Health: http://localhost:8000/health/live and /health/ready

These endpoints will communicate with the PostgreSQL instance running inside Docker.

Start Full Docker Development Stack

docker compose up --build
Docker Compose uses docker-compose.override.yml by default in local development. That override adds hot reload, the published database port, pgAdmin, Mailpit, the Traefik dashboard, and the local Traefik route file at traefik/dynamic.local.yml. Startup order: db โ†’ prestart (migrations + seed) โ†’ backend.

๐ŸŒ Local Network Access via Traefik

When using the Docker development stack, services are routed through Traefik using custom .test domains. To access them, ensure the following are in your /etc/hosts file:

127.0.0.1 traefik.fastapi-template.test api.fastapi-template.test pgadmin.fastapi-template.test mail.fastapi-template.test
Services are then available at: - API: http://api.fastapi-template.test - pgAdmin: http://pgadmin.fastapi-template.test - Mailpit: http://mail.fastapi-template.test - Traefik Dashboard: http://traefik.fastapi-template.test

pgAdmin, Mailpit and the Traefik dashboard are local-only services. They are defined in docker-compose.override.yml and are not part of the base docker-compose.yaml stack.

๐Ÿ—„๏ธ Database Migrations & Seeding

This project uses Alembic for migrations and a custom script for initial data seeding.

1. Generate a New Migration

Always generate migrations after making changes to your models in app/models/.

uv run alembic revision --autogenerate -m "describe your changes"
Verify the generated script in alembic/versions/.

2. Apply Migrations

uv run alembic upgrade head

3. Seed Initial Data

To create the initial SUPER user (idempotent; the Docker prestart job runs this for you):

uv run python -m app.db.initial_data

4. Check Migrations Match the Models

uv run alembic check   # fails if a model change has no migration
The test suite also runs every migration and this check against PostgreSQL 18.

5. Purge Old Audit Records

uv run python -m app.db.maintenance --days 90

๐Ÿงช Testing

We use Pytest for our testing suite, enhanced with Testcontainers for isolated infrastructure and Hypothesis for property-based testing.

Run All Tests

uv run pytest

Coverage (branch-aware, minimum 90%) is reported on every run; configuration is in pyproject.toml.

How the suite works

  • A PostgreSQL 18 container is started once per session (Testcontainers), so Docker must be running.
  • The schema is created by running the real Alembic migrations, and alembic check guards against drift.
  • Every test starts from empty tables; use the make_user, super_user, admin_user, normal_user fixtures and auth_headers(user).
  • Outgoing email is captured by the outbox fixture instead of being sent.
  • Tests are grouped by feature: tests/api/test_auth.py, test_users.py (full RBAC matrix), test_todos.py, test_admin.py, test_platform.py (health, errors, headers, rate limits), plus tests/aws, tests/core, tests/db and tests/middleware.

Property-based & API fuzzing

  • Hypothesis covers hashing and input normalisation (tests/core).
  • Schemathesis fuzzes the running API for server errors. CI does this in docker-compose-test.yml. Run it only against a disposable database, because it creates, changes and deletes data. Locally:
    uvx schemathesis run http://localhost:8000/openapi.json --checks not_a_server_error \
      -H "Authorization: Bearer <token>" \
      --exclude-path /api/v1/admin/dashboard/error-test \
      --exclude-path /api/v1/login/logout \
      --exclude-path /api/v1/users/password \
      --exclude-path /api/v1/users/me \
      --exclude-path-regex '/api/v1/users/\{id\}'
    
    The excluded routes either fail on purpose or can revoke or change the token's own account, which leaves the rest of the run unauthenticated.

๐Ÿ“ง Email Testing (Mailpit)

Local email is captured by Mailpit:

Endpoints send email with app.core.email.queue_email. By default it uses FastAPI BackgroundTasks, so SMTP latency never blocks a request. If EMAIL_QUEUE_URL is set (AWS), it puts the message on SQS and the worker (app/aws/worker.py) sends it. If SMTP is not configured (SMTP_HOST or EMAILS_FROM_EMAIL empty), sending is skipped with a warning.

๐ŸŽจ Email Templates (MJML)

Templates live in app/email-templates:

  • src/: MJML sources (edit these).
  • build/: compiled HTML used at runtime. It is committed, so the app has no Node.js dependency.

After editing a template, rebuild (requires Node.js):

./scripts/build-email-templates.sh

Rendering (app/core/email.py) uses Jinja2 with autoescaping, so user-provided values such as names cannot inject HTML.

๐Ÿงน Linting & Formatting (Ruff)

We use Ruff for linting and formatting.

Run Linter

uv run ruff check .

Fix Linting Errors

uv run ruff check --fix .

Run Formatter

uv run ruff format .

โš“ Automated Code Quality (Prek)

We use Prek (a Rust-powered Git hook manager) to automate code quality and security checks before every commit. These hooks enforce linting, type checking, and security standards automatically.

Install Git Hooks

You must install the hooks locally to enable the automation:

uv run prek install

Run Hooks Manually

You can run all configured quality checks manually at any time:

uv run prek run --all-files
Note: The hooks run whitespace, YAML and large-file checks, Ruff, Mypy, Bandit, a uv lock sync and a Zensical build.

๐Ÿ” Type Checking

We use Mypy for static type checking.

uv run mypy app

๐Ÿ›ก๏ธ Security Analysis (Bandit)

We use Bandit to perform automated security linting and identify potential vulnerabilities in the application code.

# Run security scan
uv run bandit -c pyproject.toml -r app
Note: Bandit also runs as a Prek hook and in CI.

๐Ÿค– AI Coding Assistants

All assistants follow the same rules in AGENTS.md. See AI-Driven Development.

๐Ÿ“œ API Contract

openapi.json is the contract consumed by the frontend's generated client. After changing routes or schemas, regenerate and commit it (CI fails on drift):

uv run python scripts/export-openapi.py openapi.json

๐Ÿš€ Performance Profiling

We use py-spy and Scalene to monitor and optimize application performance.

1. Real-time Profiling (py-spy)

py-spy is a sampling profiler for Python programs. It lets you visualize what your Python program is spending time on without restarting the program or modifying the code.

Record a Flame Graph

# Get the process ID of the running FastAPI app
# Then run:
uv run py-spy record -o profile.svg --pid <PID>

Top view (like 'top' but for Python functions)

uv run py-spy top --pid <PID>

On macOS, py-spy needs sudo.

2. Deep Memory & CPU Analysis (Scalene)

Scalene is a high-performance CPU, GPU, and memory profiler for Python that does a number of things other Python profilers do not and cannot do.

Profile the FastAPI application

# Send some requests, then stop the server with Ctrl+C to write the profile
uv run scalene run -m uvicorn app.main:app

# Open the line-by-line CPU and memory report
uv run scalene view
Note: scalene run saves the profile to scalene-profile.json. Use uv run scalene view --cli to read it in the terminal.

๐Ÿ“ˆ Observability & Monitoring

This project features enterprise-grade observability to monitor, debug, and optimize your API in real-time.

Prometheus Metrics

We use the prometheus-fastapi-instrumentator to automatically collect and expose performance metrics for your FastAPI application.

Accessing Metrics

The metrics are exposed by the application (unless METRICS_ENABLED=False) at: - Endpoint: http://localhost:8000/metrics

You can configure your Prometheus server to scrape this endpoint to generate real-time monitoring dashboards (e.g., in Grafana) to track: - Request latency. - Request counts by status code. - Endpoint-specific performance.

Distributed Tracing (OpenTelemetry)

Set OTEL_EXPORTER_OTLP_ENDPOINT (OTLP/HTTP, e.g. http://otel-collector:4318) to export traces for every request and SQL query. The standard OTEL_* variables (headers, sampler, resource attributes) are honoured. Trace IDs are added to log lines as trace_id.

Structured Logging (Structlog & Rich)

All logs, including Uvicorn's and libraries', go through Structlog: human-readable console output when ENVIRONMENT=local, and one JSON object per line everywhere else. Each line includes request_id (from the X-Request-ID header, or generated) and, once authenticated, user_id. Set the level with LOG_LEVEL.

Why Structured Logging?

  • Local DX: Rich provides color-coded logs and enhanced traceback visualization.
  • Searchability: Easily filter logs by specific keys (e.g., event, level, timestamp).
  • Observability: Integrates seamlessly with log aggregation services (like ELK stack or Datadog).

For more information on logging configuration, see app/core/logger.py.

Error Tracking (Sentry)

This project integrates Sentry for proactive error tracking and performance monitoring, utilizing the native FastAPI integration for enhanced trace fidelity.

Configuration

To enable Sentry, you need to provide your Sentry DSN (Data Source Name).

  1. Get your DSN:
  2. Log in to your Sentry Dashboard.
  3. Create a project in your Sentry dashboard.
  4. Find your DSN under Settings > Projects > [Your Project] > Client Keys (DSN).

  5. Update Environment Variable: Add your DSN to the .env file:

    SENTRY_DSN="https://your-key@sentry.io/your-project-id"
    

  6. Restart Application: Once the environment variable is set, the Sentry SDK will automatically initialize on startup and begin capturing unhandled exceptions. Tune SENTRY_TRACES_SAMPLE_RATE (default 0.1); PII is not sent.

Note: If SENTRY_DSN is not provided, the Sentry SDK will remain inactive, ensuring no errors are logged to the service during local development.