Skip to main content

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

Metadata

Release files for fastapi-middleware-toolkit 0.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for fastapi-middleware-toolkit 0.1.1
File Size Uploaded Provenance Actions
fastapi_middleware_toolkit-0.1.1.tar.gz 9.6 kB With provenance Details for fastapi_middleware_toolkit-0.1.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for fastapi-middleware-toolkit 0.1.1
File Interpreter ABI Platform Actions
fastapi_middleware_toolkit-0.1.1-py3-none-any.whl Python 3 none any Details for fastapi_middleware_toolkit-0.1.1-py3-none-any.whl

Total release size: 17.5 kB

Release files / fastapi_middleware_toolkit-0.1.1.tar.gz

Download URL fastapi_middleware_toolkit-0.1.1.tar.gz
Size 9.6 kB
Tags Source
SHA-256 checksum
How to use checksums
40c8afd6d6a12872c6042183d451735eacc59cecc84a7cb82898f5af72e5f98c
BLAKE2b-256 checksum
How to use checksums
aeecacf3c1f847dba203f22ee887ea7bea3325a30e1eebdd2634de853e1571ce
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

Release files / fastapi_middleware_toolkit-0.1.1-py3-none-any.whl

Download URL fastapi_middleware_toolkit-0.1.1-py3-none-any.whl
Size 7.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
fe6dff16ced00e10de736897474ea663d6104a6f42c4292e7a5cb33cf938a589
BLAKE2b-256 checksum
How to use checksums
7b539fc843e265fdd1f9838c78cd663960f7e7babc8a2fd7c8ff150a4cf10036
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

Security for fastapi-middleware-toolkit 0.1.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for fastapi_middleware_toolkit-0.1.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.1 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page