Skip to main content

UsageFlow for FastAPI

Meter selected FastAPI routes and inspect their traces in the UsageFlow Console.

Use Python 3.10 or newer. Although the current package metadata advertises Python 3.6+, the source uses Python 3.10 syntax.

1. Install

python -m pip install usageflow-fastapi uvicorn

View usageflow-fastapi on PyPI.

2. Set the API key

Create an application and API key in the Console, then set it in the process environment:

export USAGEFLOW_API_KEY="your-api-key"

The package does not require python-dotenv.

3. Register the middleware

Use FastAPI/Starlette's add_middleware before the application starts:

import os

from fastapi import FastAPI
from usageflow.fastapi import UsageFlowMiddleware

app = FastAPI()

app.add_middleware(
    UsageFlowMiddleware,
    api_key=os.environ["USAGEFLOW_API_KEY"],
)


@app.get("/api/hello")
async def hello():
    return {"message": "hello"}

FastAPI applications should let app.add_middleware(...) supply app; do not construct UsageFlowMiddleware around the application yourself. Add it before serving the application and before any code causes Starlette's middleware stack to be built.

4. Select routes in the Console

For the application that owns the API key, add a monitoringPaths entry for the first route:

method: GET
url: /api/hello

Use whitelistEndpoints for routes that must be skipped. A whitelist match wins over a monitoring match. The middleware refreshes Console configuration about every 10 seconds.

Important: an empty monitoring map skips all requests. It does not enable monitor-all behavior. Configure a monitoring path and wait for a refresh before testing.

Methods can be an HTTP method or *. URL * matches every path. A URL that contains * acts as a prefix after the * characters are removed, not as a general glob or regular expression. For example, /api/users/* matches route templates beginning with /api/users/.

Current limitation: when several URL patterns use the same method, only the first pattern may be evaluated. Prefer one prefix or * entry per method.

FastAPI route selection uses the route template. For @app.get("/users/{user_id}"), configure /users/{user_id} or a matching prefix such as /users/*, rather than a concrete path such as /users/123.

5. Send a request

Save the example as app.py, start it, allow up to 10 seconds for the first configuration refresh, then call the monitored route:

uvicorn app:app
curl -i http://127.0.0.1:8000/api/hello

6. Verify the first Trace

Open the application's Traces view in the Console and confirm a GET /api/hello trace appears. If it does not appear, wait for another refresh and send one more request.

Production and security notes

  • UsageFlow records request method, route/path information, client and user-agent data, headers, query/path parameters, and supported request bodies (JSON, form, multipart, or text). It records response status, headers, duration, and schema information. The response body is observed to derive schema and response-based usage but is not attached as full response-body trace metadata.
  • Tracked responses are returned as streaming responses, and response post-processing occurs after streaming completes. The middleware replaces an existing response background task, so do not enable it on routes that depend on FastAPI or Starlette response background tasks.
  • Request header names containing key are redacted. Other headers and body fields are not automatically redacted, so avoid monitoring routes that expose secrets unless your data handling policy allows it.
  • Policy identity may come from a path parameter, query parameter, request body field, header, bearer-token claim, cookie, or configured claim in a JWT cookie. FastAPI traces also include a userId derived from the bearer token's sub claim, then X-User-ID, then anonymous. JWTs are decoded without signature verification for identity extraction. Your application remains responsible for authentication and authorization.
  • UsageFlow connectivity and telemetry failures generally fail soft so the endpoint can continue. An explicit policy decision, including endpoint blocking or a denied usage request, can intentionally reject traffic.

Troubleshooting

  • No Trace: confirm the API key belongs to the selected Console application, monitoringPaths is not empty, the method and route template match, and the route is not whitelisted. Wait at least 10 seconds after Console changes.
  • Dynamic route does not match: configure the FastAPI template (/users/{user_id}) or a matching prefix, not one concrete request path.
  • Application does not connect: confirm USAGEFLOW_API_KEY is present in the server process and outbound secure WebSocket access is allowed.
  • Request is denied: check the application's UsageFlow endpoint and usage policies. Fail-soft connectivity behavior does not override an explicit policy denial.

Metadata

Release files for usageflow-fastapi 0.3.5

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for usageflow-fastapi 0.3.5
File Size Uploaded Provenance Actions
usageflow_fastapi-0.3.5.tar.gz 12.3 kB Without provenance Details for usageflow_fastapi-0.3.5.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for usageflow-fastapi 0.3.5
File Interpreter ABI Platform Actions
usageflow_fastapi-0.3.5-py3-none-any.whl Python 3 none any Details for usageflow_fastapi-0.3.5-py3-none-any.whl

Total release size: 20.5 kB

Release files / usageflow_fastapi-0.3.5.tar.gz

Download URL usageflow_fastapi-0.3.5.tar.gz
Size 12.3 kB
Tags Source
SHA-256 checksum
How to use checksums
0598b8114da1f83f1a210d21947e992b6c550cdde8394ab11104592e2c45c5e9
BLAKE2b-256 checksum
How to use checksums
20a77bc2958c815dca43c97e01a3b15a33599176e61df40ab1f8130c3039b6a7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.0

Release files / usageflow_fastapi-0.3.5-py3-none-any.whl

Download URL usageflow_fastapi-0.3.5-py3-none-any.whl
Size 8.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
851516f03d96118ccc03bb3591a896b170322e1283a0cbfb16ec20c9dbf6b16a
BLAKE2b-256 checksum
How to use checksums
7ba0c7b654adacf4f385d87f7acdd1c36ccabf005c3c189a28ae3baa62c78b3a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.0

Security for usageflow-fastapi 0.3.5

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page