# FastAPI quickstart

Init and instrument the Python SDK at startup and tag each request with middleware and track().

AI Spendbook documentation, Your app's data. Web page: https://www.aispendbook.com/docs/quickstart-fastapi

The [Python SDK](https://www.aispendbook.com/docs/python-sdk) records the token usage of every Anthropic, OpenAI and Google Gemini call your FastAPI app makes. A middleware tags each request with its customer and user, and a decorator adds the feature.

## 1. Install and configure

```bash
pip install git+https://github.com/AISpendbook/aispendbook-python fastapi uvicorn anthropic
export SPENDBOOK_API_KEY=afk_your_key
export SPENDBOOK_ENDPOINT=https://www.aispendbook.com
export ANTHROPIC_API_KEY=sk-ant-...
```

Create the ingestion key in **Integrations** under **SDK / HTTP ingestion**. The SDK sends events to `https://www.aispendbook.com/api/v1/ingest/batch`.

## 2. Init, instrument and track

```python
import os
from contextlib import asynccontextmanager

import anthropic
from fastapi import FastAPI
from pydantic import BaseModel

import spendbook
from spendbook import track

MODEL = os.environ["ANTHROPIC_MODEL"]


@asynccontextmanager
async def lifespan(app: FastAPI):
    spendbook.init()        # reads SPENDBOOK_API_KEY / SPENDBOOK_ENDPOINT
    spendbook.instrument()  # records usage from the anthropic, openai and google-genai clients
    yield
    spendbook.shutdown(timeout=5)  # sends what is still queued


app = FastAPI(lifespan=lifespan)
claude = anthropic.AsyncAnthropic()


class AttributionMiddleware:
    """Opens a track() context for every request. Derive the ids from your authenticated
    session in production rather than trusting raw headers."""

    def __init__(self, app):
        self.app = app

    async def __call__(self, scope, receive, send):
        if scope["type"] != "http":
            return await self.app(scope, receive, send)
        headers = {k.decode().lower(): v.decode() for k, v in scope.get("headers", [])}
        async with track(customer_id=headers.get("x-customer-id"), user_id=headers.get("x-user-id")):
            await self.app(scope, receive, send)


app.add_middleware(AttributionMiddleware)


class Question(BaseModel):
    question: str


@app.post("/answer")
@track(feature="answer")  # merged with the request's customer and user
async def answer(req: Question) -> dict:
    message = await claude.messages.create(
        model=MODEL,
        max_tokens=512,
        messages=[{"role": "user", "content": req.question}],
    )
    return {"answer": "".join(b.text for b in message.content if b.type == "text")}
```

- `init()` and `instrument()` run once at startup. `shutdown()` at the end of the lifespan sends events still in the queue.
- Attribution is held in a context variable, so concurrent requests never share a customer id. Calls made in helpers and in asyncio tasks the request creates are attributed to that request.
- A `track()` nested inside another merges with it: the inner values win, and the request's customer stays.
- Events are queued in memory and sent by a background thread, so a slow or unreachable AI Spendbook never blocks a request. Prompt text is not sent.
- Calls made with other clients can be recorded with `spendbook.record()`. See the [Python SDK](https://www.aispendbook.com/docs/python-sdk) page.

## Check it works

1. In the app, open **Integrations**. Under **Add a source**, find **SDK / HTTP ingestion** and choose **Set up**.
2. Go to the **Test event** step. Use the key you just created, or paste the one your service uses, and choose **Send test event**.
3. Wait for the **Test event received** notice. It means the key and the ingestion API work. If you see **Accepted, but not visible yet**, choose **Send again** after a minute. The test event has zero tokens, so it adds no cost, and it carries the feature `spendbook-connection-test` so you can filter it out.
4. Then make one AI call through your own code and open **Usage Explorer**, filtered to the feature `answer`. During onboarding, the SDK step shows **Last event received** once events arrive.
