Skip to main content

🚀 Easy FastAPI Setup Kit - Production-ready FastAPI boilerplate with logging, error handling, metrics, security headers, and more

Project description

🚀 FastAPI Bootstrap

Production-ready FastAPI boilerplate with batteries included

Language: 한국어 | English

Python Version License: MIT Tests


✨ Features

  • 📝 Structured Logging — Loguru-based logging with request tracking & trace IDs
  • 🛡️ Exception Handling — Centralized error handling with customizable responses
  • 📊 Prometheus Metrics — Built-in /metrics endpoint 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, status
  • http_request_duration_seconds — Request latency histogram
  • http_requests_in_progress — Current active requests
  • http_request_size_bytes — Request body size
  • http_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: nosniff
  • X-Frame-Options: DENY
  • Content-Security-Policy
  • Referrer-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

fastapi_bootstrap-0.2.3.tar.gz (110.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fastapi_bootstrap-0.2.3-py3-none-any.whl (43.2 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_bootstrap-0.2.3.tar.gz.

File metadata

  • Download URL: fastapi_bootstrap-0.2.3.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

Hashes for fastapi_bootstrap-0.2.3.tar.gz
Algorithm Hash digest
SHA256 d9a744d14bc98dbeb2ad02fbc86876d26e253157dee479550cf26302ec79ce17
MD5 deb12c12e76edac63761412b3b1dfd1b
BLAKE2b-256 845abae4c7c99cfef98cf92c48a49ac9f1051b1106faec6d593712b1954015bc

See more details on using hashes here.

File details

Details for the file fastapi_bootstrap-0.2.3-py3-none-any.whl.

File metadata

File hashes

Hashes for fastapi_bootstrap-0.2.3-py3-none-any.whl
Algorithm Hash digest
SHA256 b5d3c6cbf9da64e6b817ad8e29f29d7c931a69c7761bf337851dffb66a03a067
MD5 d0e9a3cf21af2d5b521d34b4a63091f0
BLAKE2b-256 0a850d7c384e48b75047b793069ae5e0028faadaa08039e41622b212d3085b9f

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page