Skip to main content

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.
  • metrics: Pre-configured route handler exposing metrics in OpenMetrics / Prometheus exposition format.
  • Access log filtering: Built-in EndpointFilter suppresses noisy GET /metrics access logs in Uvicorn.

2. Distributed Tracing (OpenTelemetry)

  • setup_opentelemetry: One-line configuration for OpenTelemetry tracing.
    • Configures TracerProvider, Resource attributes, and BatchSpanProcessor with an OTLP gRPC exporter.
    • Instruments FastAPI endpoints and Python logging for trace correlation.

3. Correlation ID & Contextual Logging

  • CorrelationIDMiddleware: Inspects or generates an X-Correlation-ID HTTP header, propagating it across request context and returning it in responses.
  • LogContextMiddleware: Captures client information (such as client IP, respecting X-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 Unauthorized
    • LookupError $\to$ 404 Not Found
    • ValueError $\to$ 400 Bad Request
    • ConnectionRefusedError $\to$ 503 Service Unavailable
    • NotImplementedError $\to$ 501 Not Implemented
    • AppError / 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.8.7

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-commons 0.8.7
File Size Uploaded Provenance
fastapi_commons-0.8.7.tar.gz 24.4 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for fastapi-commons 0.8.7
File Interpreter ABI Platform
fastapi_commons-0.8.7-py3-none-any.whl Python 3 none any Details

Total release size: 49.4 kB

Release files / fastapi_commons-0.8.7.tar.gz

Download URL fastapi_commons-0.8.7.tar.gz
Size 24.4 kB
Tags Source
SHA-256 checksum
How to use checksums
61746f2ddeebbb4f3dbec33c9aa83503ab6e481df9217d0a8ed82377e60fab12
BLAKE2b-256 checksum
How to use checksums
8814d61a27857a53a5f75fa572e8ceff135184df89b435af3455729b03df90a3
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.8.7-py3-none-any.whl

Download URL fastapi_commons-0.8.7-py3-none-any.whl
Size 25.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
a9756480a0965c0778239505a6747bdbe37e451f13d57642745ee9ce2423688b
BLAKE2b-256 checksum
How to use checksums
78fb4d50f42a098147ca269fd02e7ec84ac64c5480d262c24f80b96960ccd833
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.8.7

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.

Release history Release notifications | RSS feed

This release

0.8.7 This release

2 release files No 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