🚀 Easy FastAPI Setup Kit - Production-ready FastAPI boilerplate with logging, error handling, and more
Project description
🚀 FastAPI Bootstrap
✨ Overview
FastAPI Bootstrap is a production-ready FastAPI boilerplate that includes everything you need to build robust APIs quickly. It provides pre-configured logging, error handling, request/response tracking, and more out of the box.
Stop writing the same boilerplate code for every FastAPI project. Start building features immediately with FastAPI Bootstrap.
🎯 Key Features
- 📝 Smart Logging — Structured logging with Loguru, request/response tracking, and trace IDs
- 🛡️ Exception Handling — Centralized error handling with customizable error responses
- 🔍 Request Tracing — OpenTelemetry integration with automatic trace ID propagation
- 🎨 Custom API Route — Enhanced APIRoute with automatic request/response logging
- ⚡️ Type Safety — Pydantic V2 integration for robust data validation
- 🏥 Health Checks — Built-in health check endpoint
- 📚 Auto Documentation — Automatic OpenAPI/Swagger UI generation
- 🔧 Highly Configurable — Customize logging, CORS, middleware, and more
- 🚀 Production Ready — Graceful shutdown, environment-based configuration
📦 Installation
pip install fastapi_bootstrap
🚀 Quick Start
See examples/ directory for complete, runnable examples.
Simple Example
# Run the example
python examples/simple/app.py
# Visit
http://localhost:8000/v1/docs
Basic Usage
from fastapi import APIRouter
from fastapi_bootstrap import create_app, LoggingAPIRoute
# Create your API router
router = APIRouter(route_class=LoggingAPIRoute)
@router.get("/hello")
async def hello():
return {"message": "Hello, World!"}
# Create the app with minimal configuration
app = create_app(
[router],
title="My API",
version="1.0.0",
)
Run the app
uvicorn main:app --host 0.0.0.0 --port 8000
With Full Configuration
from fastapi import APIRouter, Depends
from fastapi_bootstrap import create_app, LoggingAPIRoute, get_logger
logger = get_logger()
router = APIRouter(route_class=LoggingAPIRoute)
@router.get("/api/hello")
async def hello():
logger.info("Hello endpoint called")
return {"message": "Hello, World!"}
async def startup_handler(app):
logger.info("Application starting up...")
# Initialize database, connections, etc.
async def shutdown_handler(app):
logger.info("Application shutting down...")
# Cleanup resources
app = create_app(
api_list=[router],
title="My Production API",
version="1.0.0",
prefix_url="/api/v1",
graceful_timeout=10,
docs_enable=True,
docs_prefix_url="/api/v1",
health_check_api="/healthz",
startup_coroutines=[startup_handler],
shutdown_coroutines=[shutdown_handler],
stage="prod", # dev, staging, prod
)
📖 Core Components
1. create_app()
The main function to create a FastAPI application with all features enabled.
Parameters:
api_list: List of APIRouter instancestitle: API titleversion: API versionprefix_url: URL prefix for all routesgraceful_timeout: Seconds to wait before shutdown (default: 10)- Set to
0for instant shutdown (recommended for dev) - Set to
10-30for production (allows in-flight requests to complete)
- Set to
docs_enable: Enable/disable API documentation (default: True)health_check_api: Health check endpoint path (default: "/healthz")startup_coroutines: List of async functions to run on startupshutdown_coroutines: List of async functions to run on shutdownstage: Environment stage (dev/staging/prod)
2. LoggingAPIRoute
Enhanced APIRoute class that automatically logs all requests and responses with trace IDs.
from fastapi import APIRouter
from fastapi_bootstrap import LoggingAPIRoute
router = APIRouter(route_class=LoggingAPIRoute)
3. get_logger()
Get a pre-configured Loguru logger instance.
from fastapi_bootstrap import get_logger
logger = get_logger()
logger.info("Application started")
logger.error("Something went wrong")
4. BaseModel
Enhanced Pydantic BaseModel with sensible defaults.
from fastapi_bootstrap import BaseModel
class UserRequest(BaseModel):
name: str
email: str
age: int = 0
5. Exception Handling
Automatic exception handling with customizable error responses.
from fastapi_bootstrap.exception import BadRequestHeaderError, InvalidAccessTokenError
# Raise custom exceptions
raise BadRequestHeaderError("Invalid header format")
raise InvalidAccessTokenError("Token expired")
🔧 Environment Variables
Configure the application using environment variables:
# Logging
export LOG_LEVEL=INFO # DEBUG, INFO, WARNING, ERROR, CRITICAL
export LOG_JSON=false # true for JSON logs, false for pretty logs
export LOG_STRING_LENGTH=5000 # Max length of logged strings
# Application
export CONFIG_FILE=config.yaml # Configuration file path
📝 Logging Features
FastAPI Bootstrap includes advanced logging capabilities:
- Structured Logging: JSON or pretty-formatted logs
- Request/Response Logging: Automatic logging of all API calls
- Trace ID Propagation: Track requests across services with OpenTelemetry
- Context Binding: Attach contextual information to log entries
- Log Truncation: Automatically truncate long log messages
- Standard Library Integration: Captures logs from uvicorn, fastapi, and other libraries
Example log output:
2024-12-28 22:30:15.123 | INFO | app.py:main:42 | request | abc123def | GET | /api/v1/users | {"query": "active"}
2024-12-28 22:30:15.234 | INFO | app.py:main:42 | response | abc123def | GET | /api/v1/users | 200 | {"users": [...]}
🎨 Example Application
See example.py for a complete example with:
- Configuration management
- Service initialization
- Dependency injection
- Custom middleware
- Startup/shutdown handlers
🧪 Testing
# Install dev dependencies
pip install -e ".[dev]"
# Run tests
pytest tests/
# Run with coverage
pytest tests/ --cov=fastapi_bootstrap --cov-report=html
🛠️ Development
# Clone the repository
git clone https://github.com/bestend/fastapi_bootstrap.git
cd fastapi_bootstrap
# Install in development mode
pip install -e ".[dev]"
# Run linting
ruff check src/ tests/
# Format code
ruff format src/ tests/
# Type checking
mypy src/
📚 Advanced Usage
Custom Exception Handlers
from fastapi_bootstrap.exception import ErrorInfo, get_exception_definitions
# Add custom exception
class CustomError(Exception):
pass
# Register custom error info
get_exception_definitions()[CustomError] = ErrorInfo(
status_code=400,
msg="Custom error occurred",
log_level="warning"
)
Custom Middleware
from starlette.middleware.base import BaseHTTPMiddleware
class CustomMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
# Pre-processing
response = await call_next(request)
# Post-processing
return response
app = create_app(
[router],
middlewares=[CustomMiddleware]
)
📚 Examples
Complete, runnable examples are available in the examples/ directory:
1. Simple Example
Basic usage with logging, response formatting, and pagination.
python examples/simple/app.py
# Visit http://localhost:8000/v1/docs
2. Auth Example
OIDC/Keycloak authentication with role-based access control.
# Set up environment
export OIDC_ISSUER="https://keycloak.example.com/realms/myrealm"
export OIDC_CLIENT_ID="my-api"
python examples/auth/app.py
# Visit http://localhost:8000/v1/docs
3. CORS Example
Environment-specific CORS configuration and security best practices.
# Development
python examples/cors/app.py
# Production
STAGE=prod ALLOWED_ORIGINS="https://myapp.com" python examples/cors/app.py
4. External Auth Example
API Gateway/Ingress authentication with Swagger UI Bearer token support.
python examples/external_auth/app.py
# Visit http://localhost:8000/docs
See examples/README.md for detailed documentation.
🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🙏 Acknowledgments
Project details
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_bootstrap-0.1.0.tar.gz.
File metadata
- Download URL: fastapi_bootstrap-0.1.0.tar.gz
- Upload date:
- Size: 94.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
8bc1aa5fc5fe32a7b573c4a47b08764f7a183be706fb0f5b745b2d2e2421ae7e
|
|
| MD5 |
d9dc8633158e4a6d7908321972c9605e
|
|
| BLAKE2b-256 |
599f0fdd0b2e3d19ae176fe289400e15cf33b0993dabcbf1bd658908003487a0
|
File details
Details for the file fastapi_bootstrap-0.1.0-py3-none-any.whl.
File metadata
- Download URL: fastapi_bootstrap-0.1.0-py3-none-any.whl
- Upload date:
- Size: 32.9 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
7c12f575d6ea6d90a6b3b9ee30ec8f88980c56ecb890d027f3df76602f599098
|
|
| MD5 |
99290700bc5d80cc76409e03d5896197
|
|
| BLAKE2b-256 |
c286f7ffd8f9b6d3ff6770853bcad4a4a740335c445aad8c067d70c7568abd7d
|