OpenTelemetry Python FastAPI Tracing

Trace FastAPI request flows with OpenTelemetry, creating spans for routes and internal steps, then exporting OTLP batches to a collector.

PythonFastapiResilience

Code

pythonsnippet
37 lines
from fastapi import FastAPI

from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.sdk.resources import Resource
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor

provider = TracerProvider(
    resource=Resource.create({'service.name': 'inventory-api'}),
)
provider.add_span_processor(
    BatchSpanProcessor(OTLPSpanExporter(endpoint='collector:4317', insecure=True))
)
trace.set_tracer_provider(provider)

tracer = trace.get_tracer(__name__)
app = FastAPI()


async def reserve_stock(sku: str, qty: int) -> bool:
    with tracer.start_as_current_span('inventory.reserve') as span:
        span.set_attribute('inventory.sku', sku)
        span.set_attribute('inventory.quantity', qty)
        return qty < 100


@app.get('/checkout/{sku}')
async def checkout(sku: str, qty: int = 1):
    with tracer.start_as_current_span('checkout.flow') as span:
        span.set_attribute('http.route', '/checkout/{sku}')
        reserved = await reserve_stock(sku, qty)
        return {'sku': sku, 'reserved': reserved}


FastAPIInstrumentor.instrument_app(app)

How it works

OpenTelemetry Python FastAPI Tracing is built around the functions reserve_stock and checkout.

Asynchronous boundaries use await, so failures surface as exceptions at the call site rather than being swallowed. Reach for fastapi and what you get is FastAPI, trace, TracerProvider, BatchSpanProcessor, Resource — that is the whole API contact area.

It builds and returns a fresh value rather than reusing its inputs.

What to watch for

  • fastapi and opentelemetry must be installed first — the snippet imports them directly.

Using it

The primary signature is def reserve_stock(sku: str, qty: int) -> bool

Import reserve_stock from the file and call it — the rest of the code is implementation detail.

Key statements

return {'sku': sku, 'reserved': reserved}
with tracer.start_as_current_span('inventory.reserve') as span:
    span.set_attribute('inventory.sku', sku)
    span.set_attribute('inventory.quantity', qty)
    return qty < 100

Interactive Tools for This Topic

FAQ

Does `reserve_stock` modify its input?
No. The code builds and returns a new value and leaves the arguments untouched, so it is safe to call on shared or frozen data structures.
Are there third-party dependencies?
`fastapi` and `opentelemetry` — install them with the package manager before running.