Metadata-Version: 2.4
Name: usageflow-fastapi
Version: 0.3.5
Summary: FastAPI middleware for UsageFlow - Usage-based pricing made simple
Home-page: https://github.com/usageflow/usageflow-python
Author: UsageFlow
Author-email: ronen@usageflow.io
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: FastAPI
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.6
Classifier: Programming Language :: Python :: 3.7
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.6
Description-Content-Type: text/markdown
Requires-Dist: fastapi>=0.68.0
Requires-Dist: usageflow-core>=0.3.5
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary

# UsageFlow for FastAPI

Meter selected FastAPI routes and inspect their traces in the
[UsageFlow Console](https://console.usageflow.io).

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

## 1. Install

```bash
python -m pip install usageflow-fastapi uvicorn
```

[View `usageflow-fastapi` on PyPI](https://pypi.org/project/usageflow-fastapi/).

## 2. Set the API key

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

```bash
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:

```python
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:

```text
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:

```bash
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.
