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.
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:
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 |
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:
-
Start Database Services only:
-
Configure Local Environment: Keep
POSTGRES_SERVER=localhostandSMTP_HOST=localhostin.env(the defaults in.env.example). -
Run API Natively:
Withuv 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 :8000ENVIRONMENT=localthe SUPER user is seeded automatically on startup. The API will be available at: - API Documentation:
http://localhost:8000/docs - pgAdmin:
http://localhost:5050 - Mailpit UI:
http://localhost:8025 - Prometheus Metrics:
http://localhost:8000/metrics - Health:
http://localhost:8000/health/liveand/health/ready
These endpoints will communicate with the PostgreSQL instance running inside Docker.
Start Full Docker Development Stack¶
Docker Compose usesdocker-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
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/.
alembic/versions/.
2. Apply Migrations¶
3. Seed Initial Data¶
To create the initial SUPER user (idempotent; the Docker prestart job runs this for you):
4. Check Migrations Match the Models¶
The test suite also runs every migration and this check against PostgreSQL 18.5. Purge Old Audit Records¶
๐งช Testing¶
We use Pytest for our testing suite, enhanced with Testcontainers for isolated infrastructure and Hypothesis for property-based testing.
Run All Tests¶
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 checkguards against drift. - Every test starts from empty tables; use the
make_user,super_user,admin_user,normal_userfixtures andauth_headers(user). - Outgoing email is captured by the
outboxfixture 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), plustests/aws,tests/core,tests/dbandtests/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: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.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\}'
๐ง Email Testing (Mailpit)¶
Local email is captured by Mailpit:
- SMTP:
localhost:1025(inside Compose:mailpit:1025, set automatically) - Web UI: http://localhost:8025 or http://mail.fastapi-template.test
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):
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¶
Fix Linting Errors¶
Run Formatter¶
โ 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:
Run Hooks Manually¶
You can run all configured quality checks manually at any time:
Note: The hooks run whitespace, YAML and large-file checks, Ruff, Mypy, Bandit, auv lock sync and a Zensical build.
๐ Type Checking¶
We use Mypy for static type checking.
๐ก๏ธ Security Analysis (Bandit)¶
We use Bandit to perform automated security linting and identify potential vulnerabilities in the application code.
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):
๐ 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)¶
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
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:
Richprovides 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).
- Get your DSN:
- Log in to your Sentry Dashboard.
- Create a project in your Sentry dashboard.
-
Find your DSN under Settings > Projects > [Your Project] > Client Keys (DSN).
-
Update Environment Variable: Add your DSN to the
.envfile: -
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(default0.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.