A production-ready FastAPI backend project template with a modular, scalable structure. This template includes placeholders for many backend features, all controlled via feature flags for maximum flexibility.
- Modular Architecture: Clean separation of concerns with routers, services, and models
- Feature Flags: All optional features can be enabled/disabled via environment variables
- Production Safety: Built-in validation to prevent unsafe configurations
- Type Safety: Full type hints using Pydantic and Python typing
- Testing Ready: Comprehensive test suite with pytest
- Docker Support: Production-ready Dockerfile and docker-compose setup
- Lazy Loading: Heavy dependencies are only imported when features are enabled
fastapi_template/
├── app/
│ ├── main.py # Application factory with feature flags
│ ├── settings.py # Pydantic BaseSettings + feature toggles
│ ├── dependencies.py # Reusable dependency injection patterns
│ ├── logging_conf.py # Production-safe logging configuration
│ ├── decorators.py # Feature guard decorators
│ ├── routers/ # API route handlers
│ │ ├── health.py # Health check endpoints
│ │ ├── items.py # Demo CRUD endpoints (works without DB)
│ │ └── ocr.py # OCR endpoints (requires ENABLE_OCR)
│ ├── services/ # Business logic and external integrations
│ │ ├── db_postgres.py # PostgreSQL connector (placeholder)
│ │ ├── db_mongo.py # MongoDB connector (placeholder)
│ │ ├── ocr_service.py # OCR service abstraction
│ │ └── storage.py # File storage service
│ ├── models/ # SQLAlchemy models (placeholder)
│ └── tests/ # Test suite
│ ├── test_health.py
│ ├── test_feature_flags.py
│ ├── test_cors.py
│ └── conftest.py
├── requirements.txt
├── .env.example
├── Dockerfile
├── docker-compose.yml
└── README.md
- Python 3.11+
- pip
- (Optional) Docker and Docker Compose
-
Clone or copy this template:
cd fastapi_template -
Create virtual environment:
python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate
-
Install dependencies:
pip install -r requirements.txt
-
Copy environment file:
cp .env.example .env
-
Configure your
.envfile (see Configuration section below) -
Run the application:
uvicorn app.main:app --reload
The API will be available at http://localhost:8000
- API Documentation:
http://localhost:8000/docs - ReDoc:
http://localhost:8000/redoc
All configuration is done via environment variables. Copy .env.example to .env and customize:
ENVIRONMENT:development,staging, orproductionDEBUG:TrueorFalse(must beFalsein production)CORS_ORIGINS: Comma-separated list of allowed origins
Enable/disable optional features:
ENABLE_DB_POSTGRES: Enable PostgreSQL supportENABLE_DB_MONGO: Enable MongoDB supportENABLE_OCR: Enable OCR endpointsENABLE_STORAGE: Enable file storage service
- Set
ENABLE_DB_POSTGRES=Truein.env - Configure PostgreSQL connection:
POSTGRES_HOST=localhost POSTGRES_PORT=5432 POSTGRES_USER=postgres POSTGRES_PASSWORD=your_password POSTGRES_DB=fastapi_db - Install PostgreSQL driver (uncomment in
requirements.txt):pip install asyncpg
- Set
ENABLE_DB_MONGO=Truein.env - Configure MongoDB connection:
MONGO_HOST=localhost MONGO_PORT=27017 MONGO_DB=fastapi_db - Install MongoDB driver (uncomment in
requirements.txt):pip install motor
- Set
ENABLE_OCR=Truein.env - Configure OCR provider:
OCR_PROVIDER=tesseract # or google_vision, aws_textract OCR_API_KEY=your_api_key # if required - Install OCR libraries (uncomment in
requirements.txt):pip install pytesseract Pillow
- Set
ENABLE_STORAGE=Truein.env - Configure storage type:
STORAGE_TYPE=local # or s3, gcs STORAGE_PATH=./storage - For S3/GCS, install additional libraries as needed
-
Start all services:
docker-compose up -d
-
View logs:
docker-compose logs -f api
-
Stop services:
docker-compose down
-
Build image:
docker build -t fastapi_template . -
Run container:
docker run -p 8000:8000 --env-file .env fastapi_template
Run the test suite:
pytestRun with coverage:
pytest --cov=app --cov-report=htmltest_health.py: Tests health check endpointstest_feature_flags.py: Tests feature flag functionalitytest_cors.py: Tests CORS headers and preflight requestsconftest.py: Shared fixtures and test configuration
-
Create a new file in
app/routers/:from fastapi import APIRouter router = APIRouter() @router.get("/example") async def example_endpoint(): return {"message": "Hello"}
-
Mount it in
app/main.py:from app.routers import example app.include_router(example.router, prefix=settings.API_V1_PREFIX, tags=["example"])
-
Create a new file in
app/services/:from app.settings import Settings async def init_service(settings: Settings): # Initialize service pass
-
Add feature flag in
app/settings.py:ENABLE_NEW_SERVICE: bool = False
-
Conditionally initialize in
app/main.py:if settings.ENABLE_NEW_SERVICE: from app.services.new_service import init_service # Initialize service
-
Add flag to
app/settings.py:ENABLE_NEW_FEATURE: bool = False
-
Use in code with guard:
from app.decorators import feature_guard @router.get("/new-feature") async def new_feature(settings: Settings = Depends(get_settings)): feature_guard(settings, "ENABLE_NEW_FEATURE") # Feature logic
The template includes several production safety features:
- Debug Mode Validation: If
ENVIRONMENT=productionandDEBUG=True, the application will fail to start - Strict CORS: In production, only configured origins are allowed
- No Docs in Production: API documentation is disabled in production mode
- Non-root Docker User: Dockerfile runs as non-root user for security
This template is designed to evolve over multiple projects:
- Start Fresh: Copy this template for each new project
- Enable Features: Turn on only the features you need via feature flags
- Implement Placeholders: Replace placeholder code with actual implementations
- Add New Features: Add new modules following the established patterns
- Update Template: As you discover improvements, update the base template
- Share Knowledge: Document patterns and best practices
- Phase 1: Start with minimal features (health, items endpoints)
- Phase 2: Enable database as needed (PostgreSQL or MongoDB)
- Phase 3: Add specialized services (OCR, storage) when required
- Phase 4: Implement actual business logic in placeholders
- Phase 5: Add authentication, authorization, and other advanced features
GET /api/v1/health- Returns application status
GET /api/v1/items- List all itemsGET /api/v1/items/{id}- Get item by IDPOST /api/v1/items- Create new itemPUT /api/v1/items/{id}- Update itemDELETE /api/v1/items/{id}- Delete item
GET /api/v1/ocr/status- Get OCR service statusPOST /api/v1/ocr/process- Process OCR on uploaded image
- Check that the feature flag is enabled in
.env - Verify required dependencies are installed
- Check application logs for errors
- Ensure database service is running
- Verify connection credentials in
.env - Check network connectivity (Docker networking)
- Verify
CORS_ORIGINSincludes your frontend URL - Check that credentials are properly configured
- In production, ensure strict CORS settings
This template is provided as-is for use in your projects.
When improving this template:
- Maintain backward compatibility with existing feature flags
- Keep placeholder implementations simple and clear
- Document new patterns in this README
- Update tests for new features
- Follow the existing code style and structure
For issues or questions:
- Check the documentation above
- Review example implementations in the code
- Check test files for usage examples
- Review logs for detailed error messages
Happy Coding! 🚀