Production-ready FastAPI starter template with security, observability, and modern Python best practices built-in.
Project description
FastAPI Production Starter Template
A production-ready FastAPI starter kit following modern Python best practices. Built with security, observability, and developer experience in mind.
Features
Core Capabilities
- FastAPI app factory with environment-aware settings and lifespan hooks
- Structured logging via
structlogwith request correlation IDs - Extensible routing layer with dependency injection templates
- Centralized configuration using
pydantic-settingsand.env - Health & readiness checks with baseline metadata endpoints
- Comprehensive testing with pytest + httpx async client
Security & Monitoring
- Rate limiting with sliding window algorithm
- JWT authentication with token refresh support
- Request ID tracking for distributed tracing
- Prometheus metrics integration ready
- GeoIP blocking capabilities
- Security headers and CORS configuration
Developer Experience
- Type-safe configuration and schemas
- Async-first architecture
- Linting & formatting with Ruff, Black, and MyPy
- Pre-configured testing suite with coverage
- Modular architecture for easy extensibility
Quick Start
Prerequisites
- Python 3.11 or higher
- pip or uv package manager
Installation
- Clone the repository:
git clone https://github.com/thesidshah/FastAPI-Backend-Template
cd FastAPI-Backend-Template
- Create and activate a virtual environment:
python -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
- Install dependencies:
# Using pip
pip install -e ".[dev]"
# Or using uv (faster)
uv pip install -e ".[dev]"
- Copy environment configuration:
cp .env.example .env
- Run the development server:
uvicorn app.main:app --factory --host 0.0.0.0 --port 8000 --reload
Visit http://localhost:8000/docs for interactive API documentation.
Project Structure
.
├── src/
│ └── app/
│ ├── api/ # API routes and endpoints
│ │ └── routes/ # Feature-specific routers
│ ├── core/ # Core application configuration
│ │ ├── config.py # Settings management
│ │ ├── logging.py # Structured logging setup
│ │ ├── middleware.py # Middleware registration
│ │ └── lifespan.py # Startup/shutdown hooks
│ ├── middleware/ # Custom middleware
│ │ ├── auth.py # JWT authentication
│ │ ├── rate_limit.py # Rate limiting
│ │ ├── security.py # Security headers
│ │ └── monitoring.py # Request logging & metrics
│ ├── dependencies/ # FastAPI dependency providers
│ ├── schemas/ # Pydantic models
│ ├── services/ # Business logic layer
│ ├── integrations/ # External service integrations
│ └── utils/ # Utility functions
├── tests/ # Test suite
├── docs/ # Documentation
├── pyproject.toml # Project metadata & dependencies
└── .env.example # Environment configuration template
Configuration
Settings are managed via src/app/core/config.py using Pydantic settings. All configuration can be set via environment variables prefixed with APP_.
Core Settings
| Variable | Description | Default |
|---|---|---|
APP_ENVIRONMENT |
Environment (local, staging, production, test) |
local |
APP_LOG_LEVEL |
Logging level (DEBUG, INFO, WARNING, ERROR) |
INFO |
APP_LOG_FORMAT |
Log format (json or console) |
json |
APP_API_PREFIX |
API route prefix | /api/v1 |
Security Settings
| Variable | Description | Default |
|---|---|---|
APP_CORS_ALLOW_ORIGINS |
Allowed CORS origins (JSON array) | [] |
APP_ALLOWED_HOSTS |
Trusted host headers (JSON array) | ["*"] |
APP_JWT_SECRET_KEY |
Secret key for JWT signing | Required in production |
APP_JWT_ALGORITHM |
JWT algorithm | HS256 |
APP_ACCESS_TOKEN_EXPIRE_MINUTES |
Access token TTL | 30 |
Rate Limiting
| Variable | Description | Default |
|---|---|---|
APP_RATE_LIMIT_ENABLED |
Enable rate limiting | true |
APP_RATE_LIMIT_REQUESTS |
Requests per window | 100 |
APP_RATE_LIMIT_WINDOW_SECONDS |
Time window in seconds | 60 |
See .env.example for a complete list of configuration options.
Development
Running Tests
# Run all tests
pytest
# Run with coverage
pytest --cov=app --cov-report=html
# Run specific test file
pytest tests/test_health.py
Linting & Formatting
# Check code with Ruff
ruff check src tests
# Format code with Black
black src tests
# Type checking with MyPy
mypy src
Adding New Features
- Create a new router in
src/app/api/routes/<feature>.py:
from fastapi import APIRouter
router = APIRouter(prefix="/feature", tags=["feature"])
@router.get("/")
async def get_feature():
return {"message": "Feature endpoint"}
- Register the router in
src/app/api/routes/__init__.py:
from app.api.routes import feature
def register_routes(app):
app.include_router(feature.router)
-
Add business logic in
src/app/services/<feature>.py -
Create Pydantic schemas in
src/app/schemas/<feature>.py -
Write tests in
tests/test_<feature>.py
Security Features
JWT Authentication
Protected routes require a valid JWT token:
from app.middleware.auth import get_current_user
@router.get("/protected")
async def protected_route(user: dict = Depends(get_current_user)):
return {"user": user}
Rate Limiting
Rate limiting is automatically applied to all routes. Configure via environment variables or customize per-route:
from app.middleware.rate_limit import rate_limit
@router.get("/limited", dependencies=[Depends(rate_limit(requests=10, window=60))])
async def limited_route():
return {"message": "Rate limited endpoint"}
Security Headers
Automatically applied security headers include:
- X-Content-Type-Options
- X-Frame-Options
- X-XSS-Protection
- Strict-Transport-Security
- Content-Security-Policy
Logging & Observability
Structured Logging
All logs are structured using structlog with automatic request ID correlation:
import structlog
logger = structlog.get_logger(__name__)
logger.info("user_action", user_id=user.id, action="login")
Request Tracing
Every request receives a unique X-Request-ID header for distributed tracing. Enable request body logging in development:
APP_DEBUG=true
Health Checks
- Liveness:
GET /api/v1/health- Basic health check - Readiness:
GET /api/v1/health/ready- Checks downstream dependencies - Metadata:
GET /api/v1/health/info- Application metadata
Deployment
Production Checklist
- Set
APP_ENVIRONMENT=production - Configure
APP_JWT_SECRET_KEYwith a strong secret - Set appropriate
APP_CORS_ALLOW_ORIGINS - Configure
APP_ALLOWED_HOSTS - Set
APP_LOG_FORMAT=jsonfor log aggregation - Disable debug mode:
APP_DEBUG=false - Configure external dependencies (Redis, databases, etc.)
Running with Gunicorn
gunicorn app.main:app --factory \
--workers 4 \
--worker-class uvicorn.workers.UvicornWorker \
--bind 0.0.0.0:8000
Docker Deployment
Example Dockerfile:
FROM python:3.11-slim
WORKDIR /app
COPY pyproject.toml .
RUN pip install .
COPY src/ ./src/
CMD ["uvicorn", "app.main:app", "--factory", "--host", "0.0.0.0", "--port", "8000"]
Advanced Features
Phase 2: Redis & Caching
Install phase 2 dependencies:
pip install -e ".[phase2]"
Configure Redis for session storage and caching.
Phase 3: Metrics & GeoIP
Install phase 3 dependencies:
pip install -e ".[phase3]"
Enables Prometheus metrics and GeoIP blocking capabilities.
All Security Features
Install all security features:
pip install -e ".[security]"
Contributing
Contributions are welcome! Please see CONTRIBUTING.md for guidelines.
License
This project is licensed under the MIT License - see the LICENSE file for details.
Acknowledgments
Built with:
- FastAPI - Modern web framework
- Pydantic - Data validation
- Structlog - Structured logging
- Uvicorn - ASGI server
Support
- Documentation: Check the
/docsdirectory - Issues: Report bugs via GitHub Issues
- Discussions: Join GitHub Discussions for questions
Made with ❤️ for the Python community by @thesidshah
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file fastapi_production_starter-1.0.1.tar.gz.
File metadata
- Download URL: fastapi_production_starter-1.0.1.tar.gz
- Upload date:
- Size: 95.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.4
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
ffcc6feccf1ab365871fe57b26835aa571a963241929a5ff0165bf51c686a7e9
|
|
| MD5 |
3206480b3b06bc8ce5fd5354e07643a3
|
|
| BLAKE2b-256 |
f1c513ee5a9481b60d5121309219cba2e981ef9f25f9643956bb7d3baf96c126
|
File details
Details for the file fastapi_production_starter-1.0.1-py3-none-any.whl.
File metadata
- Download URL: fastapi_production_starter-1.0.1-py3-none-any.whl
- Upload date:
- Size: 37.4 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.4
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
12caccbe20519cd160649ebfdeb456e0816f42e881f67310f729aa00165683d9
|
|
| MD5 |
4b6e51ebc1111b4d963d6c6959ad6fe3
|
|
| BLAKE2b-256 |
b330405e2ff48eab98c13faf047c3ca2a54da25f8c41b0ffc5077093112a6455
|