Skip to main content

Reusable FastAPI middleware setup functions (CORS, error handlers, lifespan)

Project description

FastAPI Middleware Toolkit

Reusable FastAPI middleware setup functions for CORS, error handlers, and lifespan management.

Extracted from: GridFlow backend/src/infrastructure and backend/src/middleware

Installation

pip install fastapi-middleware-toolkit

Features

  • CORS Middleware: Secure CORS configuration with sensible defaults
  • Error Handlers: Global error handling for HTTP, validation, and custom exceptions
  • Lifespan Management: Generic lifespan context manager for startup/shutdown tasks
  • Health Check: Health check endpoint factory
  • Cache-Control Middleware: Automatic Cache-Control headers with safe defaults

Usage

CORS Middleware

from fastapi import FastAPI
from fastapi_middleware_toolkit import setup_cors_middleware

app = FastAPI()

setup_cors_middleware(
    app,
    allowed_origins=["http://localhost:3000", "http://localhost:8080"],
    allow_credentials=False,
    allowed_methods=["GET", "POST"],
    max_age=600
)

Error Handlers

from fastapi import FastAPI
from fastapi_middleware_toolkit import setup_error_handlers
from python_app_exceptions import BaseApplicationException

app = FastAPI()

# Setup with custom exception class
setup_error_handlers(app, BaseApplicationException)

Lifespan Management

from fastapi import FastAPI
from fastapi_middleware_toolkit import create_lifespan_manager

async def init_database():
    print("Database initialized")

async def cleanup_database():
    print("Database cleaned up")

lifespan = create_lifespan_manager(
    on_startup=init_database,
    on_shutdown=cleanup_database,
    service_name="my-api",
    service_version="1.0.0"
)

app = FastAPI(lifespan=lifespan)

Health Check Endpoint

from fastapi import FastAPI
from fastapi_middleware_toolkit import create_health_check_endpoint

app = FastAPI()

health_check = create_health_check_endpoint(
    service_name="my-api",
    version="1.0.0",
    additional_checks={"database": "connected"}
)

app.get("/health")(health_check)

Cache-Control Middleware

from fastapi import FastAPI, Response
from fastapi_middleware_toolkit import setup_cache_control_middleware

app = FastAPI()

# Setup with default policy (moderate caching)
setup_cache_control_middleware(app)

# Or customize the default
setup_cache_control_middleware(
    app,
    default_cache_control="public, max-age=3600"
)

# Routes can override the default
@app.get("/sensitive")
def sensitive_endpoint(response: Response):
    response.headers["Cache-Control"] = "no-store"
    return {"data": "sensitive"}

# Routes without explicit Cache-Control get the default
@app.get("/public")
def public_endpoint():
    return {"data": "public"}  # Gets default Cache-Control

API Reference

setup_cors_middleware(app, allowed_origins, ...)

Setup CORS middleware with secure defaults.

Parameters:

  • app (FastAPI): FastAPI application instance
  • allowed_origins (Union[str, List[str]]): Allowed origins
  • allow_credentials (bool): Allow credentials (default: False)
  • allowed_methods (List[str]): HTTP methods (default: ["GET", "POST"])
  • allowed_headers (List[str]): Allowed headers (default: standard headers)
  • max_age (int): Preflight cache time in seconds (default: 600)

setup_error_handlers(app, custom_exception_class=None)

Setup global error handlers.

Parameters:

  • app (FastAPI): FastAPI application instance
  • custom_exception_class (Optional[Type[Exception]]): Custom exception class

create_lifespan_manager(on_startup, on_shutdown, ...)

Create lifespan context manager.

Parameters:

  • on_startup (Optional[Callable]): Startup function
  • on_shutdown (Optional[Callable]): Shutdown function
  • service_name (str): Service name (default: "api")
  • service_version (str): Service version (default: "1.0.0")

create_health_check_endpoint(service_name, version, ...)

Create health check endpoint function.

Parameters:

  • service_name (str): Service name
  • version (str): Service version (default: "1.0.0")
  • additional_checks (Optional[Dict]): Additional health data

setup_cache_control_middleware(app, default_cache_control)

Setup Cache-Control middleware with safe defaults.

Parameters:

  • app (FastAPI): FastAPI application instance
  • default_cache_control (str): Default Cache-Control header value (default: "public, max-age=60, stale-while-revalidate=30")

Common patterns:

  • "public, max-age=60, stale-while-revalidate=30" - Moderate caching (default)
  • "no-store" - No caching for sensitive data
  • "public, max-age=3600" - 1 hour cache
  • "private, max-age=0, must-revalidate" - Browser only, always validate

Dependencies

  • fastapi>=0.100.0
  • structlog>=23.0.0

License

MIT

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_middleware_toolkit-0.1.0.tar.gz (8.8 kB view details)

Uploaded Source

Built Distribution

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

fastapi_middleware_toolkit-0.1.0-py3-none-any.whl (7.8 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_middleware_toolkit-0.1.0.tar.gz.

File metadata

File hashes

Hashes for fastapi_middleware_toolkit-0.1.0.tar.gz
Algorithm Hash digest
SHA256 74fddd44daac7235e1ee6b60a2822ec7fa6f99803152b5637e58bf2aa1eb2b4b
MD5 e6686784cd436f65b44d921269787bad
BLAKE2b-256 3ee65fad14f148b0d09aae819af4dce1d773b016050890470a51291e26d30d0a

See more details on using hashes here.

File details

Details for the file fastapi_middleware_toolkit-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for fastapi_middleware_toolkit-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 7e5e261057e53a4ce0d651481921818c043ee810be40550ba8720efd21ba4095
MD5 75d0ed94dcca22a185350d7f77d6b581
BLAKE2b-256 1b0064491713b56c9a9dea226828bc8f59454063f7510f1d19ba25a38ba80e86

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