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! π
- Create main branch (if not already created)
- Setup MongoDB project (Atlas or local instance)
- Setup Sentry project (optional, for error tracking)
- Configure environment variables (see Configuration section)
- Run with uv (see Running Locally section)
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-settingsfor flexible configuration management. - Structured Logging & Error Tracking: Integrated custom logging and Sentry support.
- 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/meendpoint for authenticated user information
- 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
- 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
- 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
- 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
Follow these steps to get the application running on your local machine for development:
-
Prerequisites:
- Git
- uv (install with
brew install uvon macOS orcurl -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
-
Install Dependencies with uv:
# Install all dependencies (production + development) uv sync --extra dev -
Configure Environment Variables:
- Copy the example environment file:
cp example.env .env
- Edit the
.envfile 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
.envfile contains configuration and potentially secrets. It is listed in.gitignoreand should never be committed to version control. - Copy the example environment file:
-
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
-
OR Run with Docker (for deployment/testing):
docker-compose up --build -d
- This uses the
docker-compose.ymlfile for containerized deployment - It builds the
appimage using uv for dependency management -druns the containers in the background
- This uses the
-
Access the Application:
- API Endpoint:
http://localhost:8000(or thePORTdefined in.env) - Interactive API Documentation (enabled in
localenvironment):- 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
- Swagger UI with OAuth2:
- API Endpoint:
-
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
-
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.
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 ECRIMAGE_TAG- Docker image tag (e.g., latest)AWS_ACCESS_KEY_ID- AWS access key for ECR accessAWS_SECRET_ACCESS_KEY- AWS secret key for ECR access (mark as secured)
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.
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 userTry it yourself:
- Start the app:
uv run uvicorn app.main:app --reload - Open Swagger UI:
http://localhost:8000/docs - Click "Authorize" button β Complete OAuth2 flow
- Test the
/api/v1/users/meendpoint with your authenticated session!
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
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/itemsBenefits:
- π 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
- 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
This boilerplate supports multiple deployment approaches:
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 appThe 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).
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:
-
Create production environment file: Create a
.envfile 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
-
Deploy:
# For local builds docker-compose up --build -d # For registry images (after CI/CD) docker-compose pull && docker-compose up -d ```## Development Tooling
pre-commit helps maintain consistent code style and quality using uv.
-
Install:
# Dependencies are already installed with `uv sync --extra dev` uv run pre-commit install -
Usage:
pre-commitruns automatically ongit commit. To run manually:uv run pre-commit run --all-files
# 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# 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 listFor the best development experience in VS Code:
-
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
-
Configure your Python interpreter:
- Open Command Palette (
Cmd+Shift+P) - Run "Python: Select Interpreter"
- Choose the one in
./.venv/bin/python(created byuv sync)
- Open Command Palette (
-
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)
- Go to VS Code Settings (
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.
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.
Contributions are welcome. Please create a feature branch, make your changes (including tests and passing pre-commit checks), and open a Pull Request.