Skip to content

abrahamy/starter

Repository files navigation

Starter

Production-ready FastAPI starter template with authentication, encryption, and modern Python best practices.

Features

Core Framework

  • FastAPI 0.128+ - Modern, fast web framework with automatic API documentation
  • SQLAlchemy 2.0 - Async ORM with full type safety
  • PostgreSQL 17 - Robust relational database with psycopg3 driver
  • Alembic - Database migration management with custom configuration
  • Pydantic 2 - Data validation and settings management

Security & Authentication

  • OAuth 2.0/OpenID Connect - Authentication via Authlib (Auth0 ready)
  • Client-side Encryption - AES-GCM encryption for PII (email, phone)
  • Secure Sessions - Signed session cookies with HTTPS-only
  • Password Hashing - Argon2 for secure credential storage
  • Trusted Host Middleware - CSRF protection

Developer Experience

  • uv - Ultra-fast Python package manager
  • Ruff - Lightning-fast linter and formatter
  • ty - Type checker for Python 3.13+
  • Structlog - Structured JSON logging for observability
  • Typer CLI - Modern CLI for database and server management
  • Pre-commit hooks - Automated code quality checks
  • Docker Compose - Local development environment

Production Ready

  • Multi-stage Docker build - Optimized container images
  • Health checks - Built-in endpoint for load balancers
  • Request tracking - X-Request-Duration header for monitoring
  • GZip compression - Automatic response compression
  • Multi-worker support - Horizontal scaling capability

Prerequisites

  • Python 3.13+
  • uv package manager
  • Docker and Docker Compose (optional, for containerized deployment)

Quick Start

Installation

# Install dependencies
uv sync

# Install pre-commit hooks
uv run pre-commit install

Running the Application

# Start development server (with auto-reload)
uv run app start

# Or with custom host/port
SERVER_HOST=0.0.0.0 SERVER_PORT=8080 uv run app start

The API will be available at http://localhost:8000 with documentation at http://localhost:8000/docs.

Using Docker

# Start all services (app + PostgreSQL)
docker compose up

# Run in detached mode
docker compose up -d

# View logs
docker compose logs -f app

# Stop services
docker compose down

Development

Database Migrations

# Create a new migration
uv run app db revision "add users table"

# Apply migrations
uv run app db up

# Revert last migration
uv run app db down

# Revert to specific revision
uv run app db down <revision_id>

Code Quality

# Lint and auto-fix issues
uv run ruff check --fix .

# Format code
uv run ruff format .

# Type check
uv run ty check .

# Run all pre-commit hooks
uv run pre-commit run --all-files

Testing

# Run all tests
uv run pytest

# Run with coverage
uv run pytest --cov=starter --cov-report=html

# Run specific test file
uv run pytest tests/test_file.py

# Run specific test function
uv run pytest tests/test_file.py::test_function_name

Configuration

Configuration is managed through environment variables using Pydantic Settings. See starter/settings.py for available options.

Key Features

  • Automatic validation - Pydantic validates all settings on startup
  • Type safety - Full type hints for all configuration values
  • Computed properties - Encryption keys derived from APP_SECRET
  • Environment-based - Different configs for dev/staging/prod

Environment Variables

# Application
APP_NAME=starter
APP_API_VERSION=0.1.0
APP_DOMAIN=localhost:8000
APP_SECRET=your-secret-key-here  # Used for encryption and session signing

# Database
DATABASE_URL=postgresql+psycopg://user:pass@localhost:5432/dbname

# Server
SERVER_HOST=0.0.0.0
SERVER_PORT=8000
SERVER_WORKERS=1

# OAuth/Authentication
AUTH_DOMAIN=your-auth0-domain.auth0.com
AUTH_CLIENT_ID=your-client-id
AUTH_CLIENT_SECRET=your-client-secret
AUTH_METADATA_URL=https://your-auth0-domain.auth0.com/.well-known/openid-configuration

# Logging
LOG_LEVEL=info

# Environment
ENVIRONMENT=development

Project Structure

starter/
├── app.py                 # FastAPI application factory
├── cli.py                 # CLI commands (Typer)
├── settings.py            # Pydantic settings
├── di.py                  # Dependency injection providers
├── database/
│   ├── models.py         # SQLAlchemy ORM models
│   ├── types.py          # Custom types (EncryptedString, Model base)
│   ├── mixins.py         # Reusable mixins (Timestamper, SoftDelete)
│   ├── enums.py          # Database enumerations
│   └── migrations/       # Alembic migrations
├── routers/              # API route handlers
│   ├── health.py        # Health check endpoint
│   └── auth.py          # OAuth authentication endpoints
├── models/               # Pydantic models (API schemas)
│   └── health.py        # Health check response schema
├── services/            # Business logic services
│   └── encryption.py   # AES-GCM encryption service
└── utils/               # Utility modules
    ├── logging.py      # Structured logging configuration
    └── middlewares.py  # Custom middleware (request duration)

API Endpoints

Health Check

GET /health

Returns the application health status, version, and timestamp.

Authentication (OAuth/OIDC)

GET /auth/login

Initiates OAuth login flow with configured identity provider.

GET /auth/callback

OAuth callback handler that processes authentication response and creates session.

GET /auth/logout

Clears user session and redirects to home page.

Contributing

  1. Create a new branch for your feature
  2. Make your changes following the code style guidelines
  3. Run tests and linters
  4. Submit a pull request

Architecture Highlights

Database Features

  • Async SQLAlchemy - Non-blocking database operations
  • Custom types - EncryptedString for transparent PII encryption
  • Reusable mixins - TimestamperMixin (created_at, updated_at), SoftDeleteMixin
  • UUID primary keys - All models use UUIDs by default
  • Automatic table naming - Snake_case convention from class names

Security Features

  • Field-level encryption - AES-GCM encryption for sensitive data
  • Deterministic key derivation - Encryption keys from APP_SECRET + salt
  • Secure sessions - HTTPS-only cookies with secret key signing
  • OAuth 2.0/OIDC - Standards-based authentication
  • CORS & Trusted Hosts - Protection against common web attacks

Observability

  • Structured logging - JSON logs with request context
  • Request duration tracking - X-Request-Duration header on all responses
  • Health check endpoint - For load balancer integration
  • Automatic middleware ordering - Request tracking, compression, CORS, sessions

License

MIT

About

Template project for starting a new FastAPI service

Resources

Stars

Watchers

Forks

Releases

Packages

Used by

Contributors

Languages