Production-ready FastAPI components with OpenTelemetry, metrics, health checks, and OIDC integration
Project description
FastAPI OTEL Common
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)
- ✅ Structured Logging - JSON-structured logs with correlation IDs
- ✅ Request ID Tracking - Distributed tracing with unique request IDs
Security & Authentication
- ✅ OIDC Authentication - Production-ready OAuth2/OIDC integration
- ✅ 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
📦 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
# ✅ Security headers
# ✅ Health check endpoints (/healthz, /readyz, /livez)
# ✅ Request logging
# ✅ Structured error handling
📚 Documentation
Full documentation is available at: https://devdenvino.github.io/fastapi_otel_common/
- Installation Guide
- Configuration
- Middleware
- OpenTelemetry Metrics
- Health Checks
- Rate Limiting
- Security
- Database
- Examples
- Contributing
🔧 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:
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}
💾 Database
Async SQLAlchemy integration:
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
🤝 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
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file fastapi_otel_common-0.1.0.tar.gz.
File metadata
- Download URL: fastapi_otel_common-0.1.0.tar.gz
- Upload date:
- Size: 27.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.14.2
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
afdaaae071f927194376f39ae3564921a086fd6771f4133478de1341955e3cc4
|
|
| MD5 |
634d40bad5362f0f9be791d0f29b1bd3
|
|
| BLAKE2b-256 |
0662323a98c7e09bd5605328d7cab1c856d1ff2753d8bbc4cbcf90d924fcf674
|
File details
Details for the file fastapi_otel_common-0.1.0-py3-none-any.whl.
File metadata
- Download URL: fastapi_otel_common-0.1.0-py3-none-any.whl
- Upload date:
- Size: 30.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.14.2
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
bd40bb87adcfe8f47816af308c89a1393481552dabdd29dcc3bc53085484bc61
|
|
| MD5 |
548ec73d3afeea743b22084709c215d8
|
|
| BLAKE2b-256 |
7ea97020c3a6ba51186633004b0c570f0bb58f6a3a9a6c12e74c5c45aa4d0f17
|