fastapi-commons
Common utilities, middleware, security, and observability helpers for production-ready FastAPI microservices.
Overview
fastapi-commons provides shared building blocks across FastAPI services to eliminate boilerplate. It integrates Prometheus metrics, OpenTelemetry distributed tracing, contextual logging with correlation IDs, OpenID Connect (OIDC) JWT and database API key authentication, and structured exception handling.
Features
1. Observability & Prometheus Metrics
PrometheusMiddleware: Tracks HTTP request counts, response statuses, in-progress requests, and request durations.- Automatically resolves parameterized route templates (e.g.
/items/{id}instead of/items/123) to prevent metric cardinality explosion. - Supports OpenTelemetry trace exemplars on duration histograms to link metrics to traces.
- Automatically resolves parameterized route templates (e.g.
metrics: Pre-configured route handler exposing metrics in OpenMetrics / Prometheus exposition format.- Access log filtering: Built-in
EndpointFiltersuppresses noisyGET /metricsaccess logs in Uvicorn.
2. Distributed Tracing (OpenTelemetry)
setup_opentelemetry: One-line configuration for OpenTelemetry tracing.- Configures
TracerProvider,Resourceattributes, andBatchSpanProcessorwith an OTLP gRPC exporter. - Instruments FastAPI endpoints and Python logging for trace correlation.
- Configures
3. Correlation ID & Contextual Logging
CorrelationIDMiddleware: Inspects or generates anX-Correlation-IDHTTP header, propagating it across request context and returning it in responses.LogContextMiddleware: Captures client information (such as client IP, respectingX-Forwarded-For).CorrelationIDFilter&LogContextFilter: Logging filters that inject correlation IDs and request context into Python log records.SHARED_LOG_CONFIG: Standard log format containing timestamps, log levels, logger names, trace IDs, span IDs, and service names.
4. Authentication & Authorization
- OIDC Token Verification (
get_token_verifier):- Validates Bearer JWT tokens against OpenID Connect (OIDC) JSON Web Key Sets (JWKS) via RS256.
- Deserializes and validates token claims into custom models using
msgspec. - Can be toggled via environment settings (
API_AUTH_ENABLED).
- Database API Key Verification (
get_api_key_verifier):- FastAPI dependency for validating API keys from request headers against database records using SQLAlchemy async sessions.
5. Exception Handling
@handle_exceptions: Decorator for endpoint functions and handlers that catches common application errors and maps them to standard HTTP exceptions:PermissionError$\to$401 UnauthorizedLookupError$\to$404 Not FoundValueError$\to$400 Bad RequestConnectionRefusedError$\to$503 Service UnavailableNotImplementedError$\to$501 Not ImplementedAppError/ValidationError$\to$500 Internal Server Error
Installation
Using uv (recommended):
uv add fastapi-commons
Or using pip:
pip install fastapi-commons
Usage Guide
Metrics & OpenTelemetry Setup
from fastapi import FastAPI
from fastapi_commons import PrometheusMiddleware, metrics, setup_opentelemetry
app = FastAPI(title="My Service")
# Setup OpenTelemetry tracing
setup_opentelemetry(app, app_name="my-service")
# Setup Prometheus metrics middleware and endpoint
app.add_middleware(PrometheusMiddleware, app_name="my-service")
app.add_route("/metrics", metrics)
@app.get("/items/{item_id}")
async def get_item(item_id: int):
return {"item_id": item_id}
Correlation ID & Logging
import logging
from fastapi import FastAPI
from fastapi_commons.middleware.correlation_id import CorrelationIDMiddleware
from fastapi_commons.middleware.log_context import LogContextMiddleware
from fastapi_commons.log.filters import CorrelationIDFilter, LogContextFilter
app = FastAPI()
# Add middlewares
app.add_middleware(CorrelationIDMiddleware)
app.add_middleware(LogContextMiddleware)
# Attach filters to your log handlers
handler = logging.StreamHandler()
handler.addFilter(CorrelationIDFilter())
handler.addFilter(LogContextFilter())
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(correlation_id)s] [%(client_ip)s] %(message)s",
handlers=[handler],
)
OIDC Authentication
from fastapi import Depends, FastAPI
from python3_commons.auth import TokenData
from fastapi_commons.auth import get_token_verifier
app = FastAPI()
class UserClaims(TokenData):
sub: str
email: str | None = None
verify_token = get_token_verifier(UserClaims)
@app.get("/protected")
async def protected_route(claims: UserClaims = Depends(verify_token)):
return {"message": f"Hello, {claims.sub}!"}
Exception Handling Decorator
from fastapi import FastAPI
from fastapi_commons.handlers import handle_exceptions
app = FastAPI()
@app.get("/find/{item_id}")
@handle_exceptions
async def find_item(item_id: int):
if item_id < 0:
raise ValueError("Item ID must be positive")
if item_id == 404:
raise LookupError("Item not found")
return {"item_id": item_id}
Configuration
Settings can be customized via environment variables:
| Environment Variable | Default | Description |
|---|---|---|
API_AUTH_ENABLED |
true |
Enable or disable API authentication enforcement |
OTLP_GRPC_ENDPOINT |
http://tempo:4317 |
OpenTelemetry gRPC collector endpoint |
OIDC_AUTHORITY_URL |
- | OpenID Connect authority / issuer URL |
OIDC_CLIENT_ID |
- | OpenID Connect client ID |
OIDC_CLIENT_SECRET |
- | OpenID Connect client secret |
OIDC_AUDIENCE |
- | Expected token audience |
OIDC_TIMEOUT |
10.0 |
OIDC HTTP request timeout (seconds) |
OIDC_VERIFY_CERT |
true |
Verify TLS certificates for OIDC requests |
License
This project is licensed under the GNU General Public License v3 (GPL-3.0). See LICENSE for details.
Contributors
See AUTHORS.md.
Metadata
Release files for fastapi-commons 0.10.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 | |
|---|---|---|---|---|
| fastapi_commons-0.10.0.tar.gz | 25.7 kB | Without provenance | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| fastapi_commons-0.10.0-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 50.7 kB
Release files / fastapi_commons-0.10.0.tar.gz
| Download URL | fastapi_commons-0.10.0.tar.gz |
|---|---|
| Size | 25.7 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
3542b5fbb43cfa5b6f1684ec660cbf3997b73ea94b5ebee12bdf9c3c7132f76d
|
|
BLAKE2b-256 checksum How to use checksums |
a5cc4e9b64840e4452d79b32e12d2489fd5f7f5ed59972e3140085bd62a29a60
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Release files / fastapi_commons-0.10.0-py3-none-any.whl
| Download URL | fastapi_commons-0.10.0-py3-none-any.whl |
|---|---|
| Size | 25.0 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
17a7f5b73cb09cd7a1640a5f36c3dc24660e20b2c24174e4fbdda77eb2fdf4c2
|
|
BLAKE2b-256 checksum How to use checksums |
f04b79f53842db2a182fd65f880f9bae01c56669ec31fc88bbcd939e29bcef22
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Security for fastapi-commons 0.10.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.