🚀 Easy FastAPI Setup Kit - Production-ready FastAPI boilerplate with logging, error handling, metrics, security headers, and more
Project description
🚀 FastAPI Bootstrap
✨ Features
- 📝 Structured Logging — Loguru-based logging with request tracking & trace IDs
- 🛡️ Exception Handling — Centralized error handling with customizable responses
- 📊 Prometheus Metrics — Built-in
/metricsendpoint with request stats - 🔒 Security Headers — HSTS, CSP, X-Frame-Options middleware
- 🔐 OIDC Authentication — JWT validation with JWKS support (optional)
- ⚡️ Type Safety — Pydantic V2 integration with enhanced BaseModel
📦 Installation
pip install fastapi-bootstrap
# With authentication support
pip install fastapi-bootstrap[auth]
🚀 Quick Start
from fastapi import APIRouter
from fastapi_bootstrap import create_app, LoggingAPIRoute
router = APIRouter(route_class=LoggingAPIRoute)
@router.get("/hello")
async def hello():
return {"message": "Hello, World!"}
app = create_app([router], title="My API", version="1.0.0")
Run with: uvicorn app:app --reload
📖 Core API
create_app()
Creates a configured FastAPI application with all features enabled.
from fastapi_bootstrap import create_app
app = create_app(
routers=[router], # List of APIRouters
title="My API", # API title
version="1.0.0", # API version
description="", # API description
docs_url="/docs", # Swagger UI path (None to disable)
openapi_url="/openapi.json",
lifespan=None, # Custom lifespan context manager
)
LoggingAPIRoute
Enhanced APIRoute that logs requests/responses with timing and trace IDs.
from fastapi import APIRouter
from fastapi_bootstrap import LoggingAPIRoute
router = APIRouter(route_class=LoggingAPIRoute)
@router.get("/users/{user_id}")
async def get_user(user_id: int):
return {"user_id": user_id}
Output:
INFO | trace_id=abc123 | GET /users/42 | 200 OK | 12.5ms
get_logger()
Get a configured Loguru logger instance.
from fastapi_bootstrap import get_logger
logger = get_logger(__name__)
logger.info("Processing started", user_id=123, action="fetch")
BaseModel
Enhanced Pydantic BaseModel with strict validation.
from fastapi_bootstrap import BaseModel
class User(BaseModel):
name: str
email: str
age: int | None = None
📊 Metrics
Enable Prometheus metrics with MetricsMiddleware.
from fastapi_bootstrap import create_app, MetricsMiddleware, get_metrics_router
app = create_app([router], title="My API")
app.add_middleware(MetricsMiddleware)
app.include_router(get_metrics_router()) # Adds /metrics endpoint
Available metrics:
http_requests_total— Total request count by method, path, statushttp_request_duration_seconds— Request latency histogramhttp_requests_in_progress— Current active requestshttp_request_size_bytes— Request body sizehttp_response_size_bytes— Response body size
🔒 Security Headers
Add security headers to all responses.
from fastapi_bootstrap import create_app, SecurityHeadersMiddleware
app = create_app([router], title="My API")
app.add_middleware(SecurityHeadersMiddleware)
Headers added:
Strict-Transport-Security(HSTS)X-Content-Type-Options: nosniffX-Frame-Options: DENYContent-Security-PolicyReferrer-Policy
🛡️ Middleware
Request ID Middleware
Adds unique request ID to all requests (via X-Request-ID header).
from fastapi_bootstrap import RequestIDMiddleware
app.add_middleware(RequestIDMiddleware)
Request Timing Middleware
Adds X-Process-Time header with request duration.
from fastapi_bootstrap import RequestTimingMiddleware
app.add_middleware(RequestTimingMiddleware)
Max Request Size Middleware
Limits request body size.
from fastapi_bootstrap import MaxRequestSizeMiddleware
app.add_middleware(MaxRequestSizeMiddleware, max_size=10 * 1024 * 1024) # 10MB
🔐 Authentication (Optional)
OIDC/JWT authentication with JWKS validation. Requires pip install fastapi-bootstrap[auth].
from fastapi import Depends
from fastapi_bootstrap import OIDCAuth, OIDCConfig
auth = OIDCAuth(
OIDCConfig(
issuer="https://your-idp.com",
audience="your-api-audience",
)
)
@router.get("/protected")
async def protected(token=Depends(auth)):
return {"user": token.sub}
⚠️ Exception Handling
Built-in exception classes for consistent error responses.
from fastapi_bootstrap.exception import (
BadRequestException,
NotFoundException,
UnauthorizedException,
ForbiddenException,
InternalServerException,
)
@router.get("/users/{user_id}")
async def get_user(user_id: int):
user = db.get(user_id)
if not user:
raise NotFoundException(detail="User not found")
return user
Error response format:
{
"error": {
"code": "NOT_FOUND",
"message": "User not found"
}
}
🌐 CORS
Enable CORS for your API.
from fastapi.middleware.cors import CORSMiddleware
app = create_app([router], title="My API")
app.add_middleware(
CORSMiddleware,
allow_origins=["https://myapp.com"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
📁 Examples
See the examples/ directory for complete examples:
| Example | Description |
|---|---|
| simple | Basic usage with logging |
| cors | CORS configuration |
| auth | OIDC authentication |
| external_auth | External auth provider |
🏥 Health Check
Built-in health check at /health:
curl http://localhost:8000/health
# {"status": "ok"}
📄 License
MIT License — see LICENSE
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.2.2.tar.gz.
File metadata
- Download URL: fastapi_bootstrap-0.2.2.tar.gz
- Upload date:
- Size: 110.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
4a641f7a43846964bce4c52c9d47658f57f0ba529bc645a500c602d49862d2e0
|
|
| MD5 |
0086e14266ff2f0dab6c6be63c05d29c
|
|
| BLAKE2b-256 |
0164263bd05d6c24df570d3b1a28168919b1762a00b10f3a323d139420a2ae12
|
File details
Details for the file fastapi_bootstrap-0.2.2-py3-none-any.whl.
File metadata
- Download URL: fastapi_bootstrap-0.2.2-py3-none-any.whl
- Upload date:
- Size: 42.8 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 |
f5888b941ae6ec2b28f3c00409c0316cf0259dc49072afe80fe9572cc006fcc5
|
|
| MD5 |
41d78cc0b186e756f46d62e78a9bf37d
|
|
| BLAKE2b-256 |
a83b8b299e732dbc0d4bf1addde89b53776a65dad6ba1aacc192fdeb9e731f06
|