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 instanceallowed_origins(Union[str, List[str]]): Allowed originsallow_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 instancecustom_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 functionon_shutdown(Optional[Callable]): Shutdown functionservice_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 nameversion(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 instancedefault_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.0structlog>=23.0.0
License
MIT
Metadata
Release files for fastapi-middleware-toolkit 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| fastapi_middleware_toolkit-0.1.0.tar.gz | 8.8 kB | Without provenance | Details for fastapi_middleware_toolkit-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| fastapi_middleware_toolkit-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for fastapi_middleware_toolkit-0.1.0-py3-none-any.whl |
Total release size: 16.6 kB
Release files / fastapi_middleware_toolkit-0.1.0.tar.gz
| Download URL | fastapi_middleware_toolkit-0.1.0.tar.gz |
|---|---|
| Size | 8.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
74fddd44daac7235e1ee6b60a2822ec7fa6f99803152b5637e58bf2aa1eb2b4b
|
|
BLAKE2b-256 checksum How to use checksums |
3ee65fad14f148b0d09aae819af4dce1d773b016050890470a51291e26d30d0a
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.10.11
|
Release files / fastapi_middleware_toolkit-0.1.0-py3-none-any.whl
| Download URL | fastapi_middleware_toolkit-0.1.0-py3-none-any.whl |
|---|---|
| Size | 7.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
7e5e261057e53a4ce0d651481921818c043ee810be40550ba8720efd21ba4095
|
|
BLAKE2b-256 checksum How to use checksums |
1b0064491713b56c9a9dea226828bc8f59454063f7510f1d19ba25a38ba80e86
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.10.11
|
Security for fastapi-middleware-toolkit 0.1.0
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.
No provenance found
None of the files in this release were uploaded with provenance metadata.
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.