Skip to content

About

My FastAPI + MongoDB + OAuth + Sentry quickstart

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Production-Ready FastAPI Boilerplate

Personal Note: This is my go-to FastAPI boilerplate that I use for all my work projects. I got tired of existing boilerplates that either miss key features or overcomplicate simple things, so I built exactly what I need. It combines MongoDB, OAuth2, uv, Docker, and auto-route discovery in a clean, production-ready package. Feel free to fork and adapt it to your needs! πŸš€

Quick Start

  1. Create main branch (if not already created)
  2. Setup MongoDB project (Atlas or local instance)
  3. Setup Sentry project (optional, for error tracking)
  4. Configure environment variables (see Configuration section)
  5. Run with uv (see Running Locally section)

Overview

This is my personal FastAPI boilerplate that I use daily at work. After trying countless existing boilerplates, none combined my favorite technologies in the exact way I wanted them. So I built this one to include everything I actually need for real production applications.

This repository provides a robust and scalable boilerplate for building FastAPI applications. It's designed with production readiness in mind, incorporating best practices for structure, configuration, logging, and deployment. It uses uv for fast, modern Python dependency management.

Why I created this: Most boilerplates either overcomplicate simple things or miss critical production features. This one strikes the perfect balance for my workflow and includes integrations for:

  • MongoDB: Configured for use with MongoDB, including support for Atlas Vector Search index creation.
  • Docker: Fully containerized for consistent development and deployment.
  • Deployment Flexibility:
    • Local development with uv and direct Python execution
    • docker-compose-pipeline.yml - CI/CD image building (used in Bitbucket Pipelines)
    • docker-compose.yml - Docker containerization for deployment
  • Clean Code Principles: Structured to promote maintainability and readability.
  • Asynchronous Operations: Leverages FastAPI's async capabilities and Gevent workers for high performance.
  • Environment-Based Configuration: Uses pydantic-settings for flexible configuration management.
  • Structured Logging & Error Tracking: Integrated custom logging and Sentry support.

Features

πŸ” Advanced OAuth2 Authentication

  • Zitadel Integration: Complete OAuth2/OIDC setup with PKCE support
  • Swagger UI Integration: OAuth2 authorization flow built into FastAPI docs
  • JWT Token Handling: Automatic token validation and user info extraction
  • Role-based Access: Admin role checking and project-specific permissions
  • User Management: /users/me endpoint for authenticated user information

πŸ—„οΈ MongoDB with Vector Search

  • Atlas Vector Search: Automatic creation and management of vector search indexes
  • Collection Management: Programmatic collection creation with error handling
  • Index Optimization: Configurable similarity metrics (cosine, euclidean, dotProduct)
  • Production Ready: Robust error handling and connection management
  • AI/ML Ready: Perfect for embeddings, semantic search, and RAG applications

πŸš€ Production-Grade Architecture

  • FastAPI Framework: Modern, fast web framework with automatic OpenAPI generation
  • uv Package Management: Lightning-fast dependency resolution and installation
  • Gunicorn + Uvicorn: Production ASGI server with worker management
  • Docker Support: Multi-stage builds with optimized image sizes
  • Environment Configuration: Pydantic-based settings with validation

πŸ› οΈ Developer Experience

  • Automatic Route Discovery: Smart route registry that auto-discovers and registers API controllers
  • Interactive API Docs: Swagger UI with OAuth2 authentication testing
  • Pre-commit Hooks: Automated code quality with flake8, pytest, and dependency analysis
  • Structured Logging: Custom logging with Sentry integration
  • Hot Reload: Fast development iteration with uvicorn --reload
  • Type Safety: Full type hints with Pydantic models

Technology Stack

  • Backend: Python 3.13, FastAPI
  • Database: MongoDB
  • Package Manager: uv (fast Python package manager)
  • WSGI Server: Gunicorn with Gevent workers
  • Containerization: Docker, Docker Compose
  • Configuration: Pydantic Settings
  • Error Tracking: Sentry (Optional)
  • Caching/Task Queue (Optional): Redis

Running Locally (Development)

Follow these steps to get the application running on your local machine for development:

  1. Prerequisites:

    • Git
    • uv (install with brew install uv on macOS or curl -LsSf https://astral.sh/uv/install.sh | sh)
    • Docker & Docker Compose (for containerized deployment)
    • A running MongoDB instance (local or cloud) and its connection string
  2. Install Dependencies with uv:

    # Install all dependencies (production + development)
    uv sync --extra dev
  3. Configure Environment Variables:

    • Copy the example environment file:
      cp example.env .env
    • Edit the .env file and provide your specific values, especially:
      • MONGO_CONNECTION_STRING: Your MongoDB connection URI.
      • MONGO_DB_NAME: The database name to use.
      • Ensure CURRENT_ENVIRONMENT=local.
      • Set PROJECT_NAME.
      • Optionally configure SENTRY_DSN, FRONTEND_URL.

    Important: The .env file contains configuration and potentially secrets. It is listed in .gitignore and should never be committed to version control.

  4. Run the Application Locally:

    # Option 1: Run with uvicorn directly (recommended for development)
    uv run uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
    
    # Option 2: Run as a Python module
    uv run python -m app
  5. OR Run with Docker (for deployment/testing):

    docker-compose up --build -d
    • This uses the docker-compose.yml file for containerized deployment
    • It builds the app image using uv for dependency management
    • -d runs the containers in the background
  6. Access the Application:

    • API Endpoint: http://localhost:8000 (or the PORT defined in .env)
    • Interactive API Documentation (enabled in local environment):
      • Swagger UI with OAuth2: http://localhost:8000/docs
        • Click "Authorize" to test OAuth2 authentication flow
        • Test protected endpoints like /api/v1/users/me
      • ReDoc: http://localhost:8000/redoc
  7. View Logs:

    # For local development (uv run)
    # Logs appear in the terminal where you ran the command
    
    # For Docker deployment
    docker-compose logs -f app
  8. Stop the Application:

    # For local development
    # Press Ctrl+C in the terminal
    
    # For Docker deployment
    docker-compose down
    ```## Configuration
    

Configuration is handled by app.core.settings.py, utilizing pydantic-settings. It loads settings from environment variables, which Docker Compose can conveniently source from the .env file during local development. Ensure all required variables (like MONGO_CONNECTION_STRING, MONGO_DB_NAME) are set either in .env for local runs or as actual environment variables in deployment environments.

Bitbucket Pipeline Environment Variables

If using Bitbucket Pipelines for CI/CD, add the following environment variables to your Bitbucket repository settings (Repository Settings > Pipelines > Repository Variables):

Required Variables:

  • PORT - Application port (e.g., 8000)
  • AWS_REGION - AWS region for ECR (e.g., us-west-2)
  • AWS_ECR_REPO_URL - ECR repository URL (e.g., 123456789012.dkr.ecr.us-west-2.amazonaws.com)
  • IMAGE_NAME - Docker image name for ECR
  • IMAGE_TAG - Docker image tag (e.g., latest)
  • AWS_ACCESS_KEY_ID - AWS access key for ECR access
  • AWS_SECRET_ACCESS_KEY - AWS secret key for ECR access (mark as secured)

Clean Code & Best Practices

The boilerplate promotes clean code through a modular structure (separating database logic, core settings, utilities, etc.), centralized configuration, type hinting, structured logging, and the use of pre-commit for automated code quality checks.

πŸš€ Advanced Capabilities Showcase

OAuth2 + Swagger UI Integration

This boilerplate includes production-ready OAuth2 authentication that works seamlessly with FastAPI's automatic API documentation:

# Protected endpoint example
@router.get("/me", response_model=UserInfo)
async def get_me(user: UserInfo = Depends(get_current_user)):
    """Get current authenticated user - test OAuth2 in Swagger UI!"""
    return user

Try it yourself:

  1. Start the app: uv run uvicorn app.main:app --reload
  2. Open Swagger UI: http://localhost:8000/docs
  3. Click "Authorize" button β†’ Complete OAuth2 flow
  4. Test the /api/v1/users/me endpoint with your authenticated session!

MongoDB Vector Search Management

Automatic creation and management of Atlas Vector Search indexes for AI/ML applications:

# Automatic vector index creation
create_vector_search_index_if_not_exists(
    collection=my_collection,
    index_name="semantic_search",
    similarity="cosine"  # or "euclidean", "dotProduct"
)

Perfect for:

  • πŸ€– RAG (Retrieval-Augmented Generation) systems
  • πŸ” Semantic search applications
  • πŸ“Š ML model serving with vector similarity
  • 🎯 Recommendation engines

Automatic Route Discovery & Registration

The boilerplate includes a smart route registry that automatically discovers and registers FastAPI routers:

# Just create a router in any file under app/api/v1/
# app/api/v1/my_feature.py
from fastapi import APIRouter

router = APIRouter()

@router.get("/items")
async def get_items():
    return {"items": []}

# The route registry automatically finds and registers this as:
# GET /api/v1/my_feature/items

Benefits:

  • πŸ”„ Zero Configuration: No manual router registration required
  • πŸ“ Convention over Configuration: Follow the folder structure, get automatic routing
  • 🧩 Modular Development: Add new API modules by simply creating files
  • πŸ” Route Discovery: Automatically scans app/api/v1/ for router objects
  • βœ… Error Handling: Robust error reporting if modules fail to load

MongoDB Integration Details

  • Connection Management: Robust connection handling via app.db.mongo_connect
  • Vector Search: Automatic Atlas Vector Search index creation and validation
  • Collection Setup: Programmatic collection management with error handling
  • Production Ready: Comprehensive error handling and retry logic

Deployment Strategies

This boilerplate supports multiple deployment approaches:

1. Local Development (Recommended)

Run directly with uv for fast development:

# Install dependencies
uv sync --extra dev

# Run with hot reload
uv run uvicorn app.main:app --reload --host 0.0.0.0 --port 8000

# Or run as module
uv run python -m app

2. CI/CD Pipeline (Bitbucket Pipelines)

The docker-compose-pipeline.yml is used in Bitbucket Pipelines to:

  • Build the Docker image using uv for dependency management
  • Tag the image for your container registry (e.g., AWS ECR)
  • Push the tagged image to the registry

This happens automatically when you push to the master branch (configure pipeline variables as mentioned in the Configuration section).

3. Production Deployment

Use the regular docker-compose.yml for containerized deployment:

Prerequisites:

  • Docker and Docker Compose installed on the target server
  • AWS credentials configured for ECR access (if using ECR images)

Setup Steps:

  1. Create production environment file: Create a .env file on the server with production environment variables:

    PORT=8000
    MONGO_CONNECTION_STRING=your-prod-mongo-uri
    MONGO_DB_NAME=your-prod-db
    SENTRY_DSN=your-sentry-dsn
    # ... other production variables
  2. Deploy:

    # For local builds
    docker-compose up --build -d
    
    # For registry images (after CI/CD)
    docker-compose pull && docker-compose up -d
    ```## Development Tooling
    

Code Quality with Pre-commit

pre-commit helps maintain consistent code style and quality using uv.

  1. Install:

    # Dependencies are already installed with `uv sync --extra dev`
    uv run pre-commit install
  2. Usage: pre-commit runs automatically on git commit. To run manually:

    uv run pre-commit run --all-files

Running Tests

# Run tests with coverage
uv run pytest --cov=app --cov-report=term --cov-fail-under=40

# Run linting
uv run flake8 app --max-line-length 120

# Run dependency analysis
uv run pydeps app --no-show

Package Management with uv

# Add a new dependency
uv add package-name

# Add a development dependency
uv add --dev package-name

# Remove a dependency
uv remove package-name

# Update dependencies
uv sync

# Show installed packages
uv pip list

VS Code Setup

For the best development experience in VS Code:

  1. Install recommended extensions:

    • Python (ms-python.python) - Core Python support
    • Black Formatter (ms-python.black-formatter) - Auto-formatting on save
    • Pylance (ms-python.vscode-pylance) - Type checking and IntelliSense
  2. Configure your Python interpreter:

    • Open Command Palette (Cmd+Shift+P)
    • Run "Python: Select Interpreter"
    • Choose the one in ./.venv/bin/python (created by uv sync)
  3. Enable format on save:

    • Go to VS Code Settings (Cmd+,)
    • Search for "format on save" and enable it
    • Black will automatically use the line length configured in pyproject.toml (120 characters)

That's it! The pre-commit hooks will catch any formatting/linting issues, so you don't need complex VS Code configuration. Just install the extensions and let the tools do their work.

Configuration Files

All tool configurations are centralized in pyproject.toml:

  • pytest - Test configuration and options
  • coverage - Code coverage settings
  • flake8 - Linting rules and exclusions
  • hatch - Build system configuration

This eliminates the need for separate .flake8, pytest.ini, or other configuration files.

Contributing

Contributions are welcome. Please create a feature branch, make your changes (including tests and passing pre-commit checks), and open a Pull Request.

About

My FastAPI + MongoDB + OAuth + Sentry quickstart

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages