This guide demonstrates how to use TrueFoundry OtelCollector along with the Traceloop SDK to instrument FastAPI applications. In this example, we’ll create a simple FastAPI application with a /greet endpoint that demonstrates how to integrate TrueFoundry’s tracing capabilities.

1

Create Tracing Project, API Key and copy tracing code

Follow the instructions in Getting Started to create a tracing project, generate API key and copy the tracing code.

2

Install Dependencies

First, you need to install the following

pip install fastapi uvicorn dotenv opentelemetry-instrumentation-fastapi==0.55b0 traceloop-sdk==0.38.12
3

Add Tracing code to FastAPI application

For FastAPI applications, we need to add the Traceloop.init() call to the application and instrument the FastAPI app with OpenTelemetry.

FastAPI Code
from dotenv import load_dotenv
from fastapi import FastAPI
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
import uvicorn
import os

# importing traceloop sdk
from traceloop.sdk import Traceloop

load_dotenv()

# Add the traceloop init code to your application
TFY_API_KEY = os.environ.get("TFY_API_KEY")
Traceloop.init(
    api_endpoint="<enter_your_api_endpoint>",
    headers = {
        "Authorization": f"Bearer {TFY_API_KEY}",
        "TFY-Tracing-Project": "<enter_your_tracing_project_fqn>",
    },
)

app = FastAPI()

@app.get("/greet")
async def root():
    return {"message": "Hi there, wishing you a great day!"}

# Instrument the FastAPI app
FastAPIInstrumentor.instrument_app(app)

if __name__ == "__main__":
    uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True, log_level="debug")
4

Run your application and view logged trace