This quickstart verifies Trace events in a FastAPI app with the trace_dependency dependency from trace-device.
Before you start
You need a secret key (sk_...) from the dashboard's Keys page and a frontend that sends an eventId (see the Web quickstarts). Send it in the x-trace-event-id header or as eventId in the request body.
- 1
Install the SDK
Terminalpip install trace-deviceTerminalexport TRACE_SECRET_KEY=sk_... export TRACE_ENDPOINT=https://id.example.comThe import name is
trace_devicebecausetraceis a standard-library module. - 2
Guard a route
The dependency reads the event id from the
X-Trace-Event-Idheader or a JSON body, verifies it, and gives your route the server-verified event. The check is a blocking HTTP call, so it runs in a worker thread and never stalls the event loop.Pythonfrom fastapi import Depends, FastAPI from trace_device.fastapi import trace_dependency app = FastAPI() @app.post("/api/signup") async def signup(event=Depends(trace_dependency(fail_open=True, reject=lambda e: e["suspectScore"] >= 60))): # event is None only with fail_open when Trace was unreachable # create the user, and store event["visitorId"] with it for later lookups return {"ok": True}A failed guard raises
HTTPExceptionwith 400 for a missing or invalid event, 403 whenrejectreturns true, 503 when Trace cannot be reached and 500 for a bad key or missing configuration.fail_open=Trueonly covers the unreachable case; a wrong key never fails open. For form posts (not JSON), send the id in theX-Trace-Event-Idheader.Start in shadow mode
For the first week, leave out
rejectand logevent["suspectScore"]andevent["reasons"]instead. Look at who would have been blocked, then pick thresholds you trust.