Skip to main content

Production-ready FastAPI components with OpenTelemetry, metrics, health checks, and OIDC integration

Project description

FastAPI OTEL Common

PyPI version Python 3.12+ License: MIT Documentation

Production-ready FastAPI components with OpenTelemetry integration, OIDC authentication, and enterprise features.

🚀 Features

Observability

  • OpenTelemetry Tracing - Full distributed tracing with OTLP export
  • OpenTelemetry Metrics - HTTP request metrics (count, duration, size)
  • Logging - Loguru integration with colorized console and OTLP export
  • Request ID Tracking - Distributed tracing with unique request IDs

Security & Authentication

  • OIDC Authentication - Production-ready OAuth2/OIDC integration
  • Role-Based Access Control (RBAC) - Client-specific role checking
  • Security Headers - OWASP-compliant security headers out of the box
  • Rate Limiting - Memory or Redis-backed rate limiting

Reliability

  • Health Checks - Kubernetes-compatible liveness/readiness/startup probes
  • Lifecycle Management - Proper startup/shutdown with resource cleanup
  • Database Management - Async SQLAlchemy with connection pooling

Developer Experience

  • Type Safe - Full type hints and PEP 561 compliance
  • Environment-Driven Config - Zero-config with sensible defaults
  • One-Line Setup - Get started with a single function call
  • AI Support - Built-in support for GitHub Copilot and Antigravity Skills

📦 Installation

# Basic installation
pip install fastapi_otel_common

# With Redis support for distributed rate limiting
pip install fastapi_otel_common[redis]

🏃 Quick Start

from fastapi_otel_common import create_app

# Create app with built-in middleware and OpenTelemetry instrumentation
app = create_app(
    title="My API",
    version="1.0.0"
)

@app.get("/")
async def root():
    return {"message": "Hello World"}

# That's it! Your app now has:
# ✅ OpenTelemetry tracing and metrics
# ✅ Loguru logging (Console + OTLP)
# ✅ Security headers
# ✅ Health check endpoints (/healthz, /readyz, /livez)
# ✅ Structured error handling

📚 Documentation

Full documentation is available at: https://devdenvino.github.io/fastapi_otel_common/

🔧 Configuration

Configure via environment variables:

# Application
APP_TITLE=My API
APP_VERSION=1.0.0
DEBUG=False

# Middleware
ENABLE_REQUEST_ID_MIDDLEWARE=True
ENABLE_SECURITY_HEADERS_MIDDLEWARE=True
ENABLE_LOGGING_MIDDLEWARE=True
ENABLE_RATE_LIMIT_MIDDLEWARE=False

# Rate Limiting
RATE_LIMIT_PER_MINUTE=60
RATE_LIMIT_PER_HOUR=1000
RATE_LIMITER_BACKEND=memory  # or 'redis' for distributed
REDIS_URL=redis://localhost:6379

# OpenTelemetry
SERVICE_NAME=my-api
SERVICE_VERSION=1.0.0
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317
ENABLE_OTEL_INSTRUMENTATION=True
ENABLE_OTEL_METRICS=True
OTEL_METRIC_EXPORT_INTERVAL=60000  # Export interval in milliseconds
OTEL_METRIC_EXPORT_TIMEOUT=5000    # Export timeout in milliseconds (prevents shutdown hangs)

🏥 Health Checks

Kubernetes-compatible health probes are automatically included:

# GET /healthz  - Liveness probe
# GET /livez    - Liveness probe (alias)
# GET /readyz   - Readiness probe (checks DB and OIDC)
# GET /startupz - Startup probe

Example Kubernetes configuration:

livenessProbe:
  httpGet:
    path: /healthz
    port: 8000
  initialDelaySeconds: 30
  periodSeconds: 10

readinessProbe:
  httpGet:
    path: /readyz
    port: 8000
  initialDelaySeconds: 10
  periodSeconds: 5

See Health Checks Documentation for details.

🛡️ Security

Includes production-ready security features:

Basic Authentication

from fastapi import Depends
from fastapi_otel_common import create_app
from fastapi_otel_common.security import get_current_user
from fastapi_otel_common.core.models import UserBase

app = create_app()

@app.get("/protected")
async def protected_route(user: UserBase = Depends(get_current_user)):
    return {"user_id": user.id, "email": user.email}

Role-Based Access Control (RBAC)

Protect endpoints with client-specific role requirements (supports OR, AND, and complex logic):

from fastapi_otel_common.security import RequireRoles, RequireAllRoles

# Require 'admin' OR 'manager' role for default client ID
@app.get("/admin/dashboard")
async def admin_dashboard(
    user: UserBase = Depends(RequireRoles(["admin", "manager"]))
):
    return {"message": f"Welcome {user.given_name}", "roles": user.roles}

# Require BOTH 'admin' AND 'auditor' roles
@app.delete(
    "/admin/system",
    dependencies=[Depends(RequireAllRoles(["admin", "auditor"]))]
)
async def dangerous_operation():
    return {"message": "Operation completed"}

See Role-Based Access Control Documentation for advanced patterns like complex boolean logic.

💾 Database

Async SQLAlchemy with multi-database support via adapter pattern:

Quick Start with SQLite (Development)

# No PostgreSQL needed! Just set DB_TYPE
DB_TYPE=sqlite
SQLITE_DB_PATH=./data/app.db

Production with PostgreSQL

DB_TYPE=postgresql
DB_USER=postgres
DB_PASS=postgres
DB_HOST=localhost
DB_PORT=5432
DB_NAME=mydb

Using in FastAPI

from fastapi import Depends
from sqlalchemy.ext.asyncio import AsyncSession
from fastapi_otel_common.database import get_db_session

@app.get("/users")
async def get_users(db: AsyncSession = Depends(get_db_session)):
    result = await db.execute(select(User))
    return result.scalars().all()

📊 Observability

Full OpenTelemetry integration for distributed tracing and metrics:

Tracing

  • Automatic request tracing
  • Database query tracing
  • Custom span creation
  • Context propagation
  • OTLP/Jaeger export

Metrics

Automatically collected HTTP metrics:

  • Request count by method, path, and status code
  • Request duration histogram in milliseconds
  • Request/response sizes histograms
  • Active requests counter
# Metrics are automatically exported to your OTLP collector
# View in Grafana, Prometheus, or any OpenTelemetry-compatible backend

See Metrics Documentation for visualization and querying.

🧪 Development

# Install with dev dependencies
pip install -e ".[dev]"

# Run tests
pytest --cov=fastapi_otel_common

# Format code
black .

# Lint
ruff check .

# Type check
mypy fastapi_otel_common

🤖 AI Agent Skills

Enhance your development environment by adding project-specific skills to your AI assistants (GitHub Copilot, Antigravity, Cursor, etc.).

Adding Skills to your Workspace

To automatically add the fastapi-otel-common skills to your project, run:

npx skills add devdenvino/fastapi_otel_common

This will set up:

  • .agent/skills/ - Custom skills for Antigravity and other agentic IDEs.
  • .github/copilot-instructions.md - Tailored instructions for GitHub Copilot.

See the AI Agent Skills Documentation for more details on how to customize these instructions.

🤝 Contributing

Contributions are welcome! Please see our Contributing Guide for details.

📝 License

This project is licensed under the MIT License - see the LICENSE file for details.

🙏 Acknowledgments

  • FastAPI team for the amazing framework
  • OpenTelemetry community for observability tools
  • slowapi for rate limiting

📧 Support

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_otel_common-0.1.4.tar.gz (45.5 kB view details)

Uploaded Source

Built Distribution

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

fastapi_otel_common-0.1.4-py3-none-any.whl (42.9 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_otel_common-0.1.4.tar.gz.

File metadata

  • Download URL: fastapi_otel_common-0.1.4.tar.gz
  • Upload date:
  • Size: 45.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.29 {"installer":{"name":"uv","version":"0.9.29","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for fastapi_otel_common-0.1.4.tar.gz
Algorithm Hash digest
SHA256 7c990d7060f360509b78b6e0fe749a57e742029161426dd593e8c4db877af3ba
MD5 3071ade50c9ec65f42316bc46c3fc01d
BLAKE2b-256 af03497131665e4110c40db38b3c1168ac63946f5db5fe1d1d7ec29cf841bf30

See more details on using hashes here.

File details

Details for the file fastapi_otel_common-0.1.4-py3-none-any.whl.

File metadata

  • Download URL: fastapi_otel_common-0.1.4-py3-none-any.whl
  • Upload date:
  • Size: 42.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.29 {"installer":{"name":"uv","version":"0.9.29","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for fastapi_otel_common-0.1.4-py3-none-any.whl
Algorithm Hash digest
SHA256 f8fce711a4aecf2fe2ec725c0c7c0bcc755d7efaef55b29fc1d644cda8822bc0
MD5 a89b930c7f0f6afe17b7d87e0a9e3c6a
BLAKE2b-256 35693e1b4a8e1b7b38f7568dd0fe550ec08a9f58a5d0fafcba073182f8c75464

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