Install OpenTelemetry in FastAPI
Python services use the vendor-neutral OpenTelemetry SDK and exporters. Use a gateway when multiple services need policy enforcement.
service.name and an environment on every service, and verify signals in the console after starting the process.pip install fastapi uvicorn opentelemetry-distro opentelemetry-exporter-otlp
opentelemetry-bootstrap -a install
export OTEL_SERVICE_NAME="recommendation-api"
export OTEL_RESOURCE_ATTRIBUTES="deployment.environment.name=production"
export OTEL_EXPORTER_OTLP_PROTOCOL="http/protobuf"
export OTEL_EXPORTER_OTLP_ENDPOINT="https://your-collector.example.com"
opentelemetry-instrument uvicorn app:app --host 0.0.0.0 --port 8000Configure OTLP authentication on the trusted exporter or collector. Use a reachable, HTTPS endpoint and do not place credentials in the client-visible code.
Add a span for business logic
Automatic instrumentation covers inbound HTTP. Manually name domain operations for meaningful trace exploration.
from fastapi import FastAPI
from opentelemetry import trace
app = FastAPI()
tracer = trace.get_tracer("recommendation-api")
@app.get("/recommendations/{category}")
def recommendations(category: str):
with tracer.start_as_current_span("recommendations.rank") as span:
span.set_attribute("recommendations.category", category)
items = ["item-1", "item-2"]
span.set_attribute("recommendations.count", len(items))
return {"items": items}Use the OpenTelemetry context propagators to correlate outbound HTTP calls and downstream Java or Node.js services.
Verify the trace
Run curl http://localhost:8000/recommendations/books and confirm the parent HTTP span and the ranking child span appear together.
If absent, check the Collector receiver port, protocol, authentication headers and sampling policy.