> ## Documentation Index
> Fetch the complete documentation index at: https://docs.routeway.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Balance & Usage

> Monitor your credit balance, review request history, and query usage analytics.

Routeway's account endpoints let you programmatically track spending and usage without visiting the dashboard. This is useful for building internal dashboards, setting up alerts, or auditing costs.

<Info>
  All endpoints on this page require a **management key**. Create one from [Dashboard → Management Keys](https://routeway.ai/dashboard/management-keys).
</Info>

## Check Your Balance

`GET /v1/account/balance` returns your current credit balance in dollars.

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    import os
    import requests

    headers = {"Authorization": f"Bearer {os.getenv('ROUTEWAY_MANAGEMENT_KEY')}"}

    response = requests.get("https://api.routeway.ai/v1/account/balance", headers=headers)
    data = response.json()

    print(f"Current balance: ${data['balance']:.2f}")
    ```
  </Tab>

  <Tab title="Node.js">
    ```javascript theme={null}
    const response = await fetch("https://api.routeway.ai/v1/account/balance", {
      headers: { Authorization: `Bearer ${process.env.ROUTEWAY_MANAGEMENT_KEY}` },
    });

    const { balance } = await response.json();
    console.log(`Current balance: $${balance.toFixed(2)}`);
    ```
  </Tab>

  <Tab title="cURL">
    ```bash theme={null}
    curl https://api.routeway.ai/v1/account/balance \
      -H "Authorization: Bearer $ROUTEWAY_MANAGEMENT_KEY"
    ```
  </Tab>
</Tabs>

**Response:**

```json theme={null}
{
  "balance": 4.20
}
```

<Tip>
  Use this endpoint to implement low-balance alerts. Poll periodically and notify your team when the balance drops below a threshold.
</Tip>

***

## Request Activity

`GET /v1/account/activity` returns a paginated list of individual request logs, including the model used, cost, and timestamp.

### Parameters

| Parameter | Type    | Default | Description                         |
| --------- | ------- | ------- | ----------------------------------- |
| `limit`   | integer | `50`    | Number of records to return (1–200) |
| `offset`  | integer | `0`     | Offset for pagination               |

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    import os
    import requests

    headers = {"Authorization": f"Bearer {os.getenv('ROUTEWAY_MANAGEMENT_KEY')}"}

    response = requests.get(
        "https://api.routeway.ai/v1/account/activity",
        headers=headers,
        params={"limit": 10, "offset": 0}
    )

    data = response.json()

    for entry in data["data"]:
        print(f"{entry['created_at']} | {entry['model']:20s} | ${entry['cost']:.5f}")

    print(f"\nShowing {len(data['data'])} of results (offset: {data['offset']})")
    ```
  </Tab>

  <Tab title="Node.js">
    ```javascript theme={null}
    const params = new URLSearchParams({ limit: "10", offset: "0" });

    const response = await fetch(
      `https://api.routeway.ai/v1/account/activity?${params}`,
      { headers: { Authorization: `Bearer ${process.env.ROUTEWAY_MANAGEMENT_KEY}` } }
    );

    const { data, limit, offset } = await response.json();

    for (const entry of data) {
      console.log(`${entry.created_at} | ${entry.model.padEnd(20)} | $${entry.cost.toFixed(5)}`);
    }
    ```
  </Tab>

  <Tab title="cURL">
    ```bash theme={null}
    curl "https://api.routeway.ai/v1/account/activity?limit=10&offset=0" \
      -H "Authorization: Bearer $ROUTEWAY_MANAGEMENT_KEY"
    ```
  </Tab>
</Tabs>

**Response:**

```json theme={null}
{
  "data": [
    {
      "model": "gpt-4o",
      "cost": 0.00042,
      "created_at": "2025-06-15T12:00:00Z"
    },
    {
      "model": "claude-sonnet-4-20250514",
      "cost": 0.00128,
      "created_at": "2025-06-15T11:58:30Z"
    }
  ],
  "limit": 10,
  "offset": 0
}
```

### Pagination

To fetch all activity, increment `offset` by `limit` until the returned `data` array is empty:

```python theme={null}
all_activity = []
offset = 0
limit = 200

while True:
    response = requests.get(
        "https://api.routeway.ai/v1/account/activity",
        headers=headers,
        params={"limit": limit, "offset": offset}
    )
    page = response.json()
    all_activity.extend(page["data"])

    if len(page["data"]) < limit:
        break
    offset += limit

print(f"Total requests: {len(all_activity)}")
```

***

## Usage Analytics

`GET /v1/account/analytics` returns aggregated usage metrics over a time window. Results are cached server-side for 5 minutes.

### Parameters

| Parameter | Type   | Default | Description                                       |
| --------- | ------ | ------- | ------------------------------------------------- |
| `period`  | string | `"30d"` | Time window: `"24h"`, `"7d"`, `"30d"`, or `"all"` |
| `model`   | string | —       | Filter metrics to a specific model ID             |

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    import os
    import requests

    headers = {"Authorization": f"Bearer {os.getenv('ROUTEWAY_MANAGEMENT_KEY')}"}

    # Get last 7 days of usage
    response = requests.get(
        "https://api.routeway.ai/v1/account/analytics",
        headers=headers,
        params={"period": "7d"}
    )

    # Check cache status
    cache_status = response.headers.get("X-Cache", "MISS")
    print(f"Cache: {cache_status}")

    analytics = response.json()
    print(analytics)
    ```
  </Tab>

  <Tab title="Node.js">
    ```javascript theme={null}
    const response = await fetch(
      "https://api.routeway.ai/v1/account/analytics?period=7d",
      { headers: { Authorization: `Bearer ${process.env.ROUTEWAY_MANAGEMENT_KEY}` } }
    );

    const cacheStatus = response.headers.get("X-Cache") ?? "MISS";
    console.log(`Cache: ${cacheStatus}`);

    const analytics = await response.json();
    console.log(analytics);
    ```
  </Tab>

  <Tab title="cURL">
    ```bash theme={null}
    # Last 7 days, all models
    curl "https://api.routeway.ai/v1/account/analytics?period=7d" \
      -H "Authorization: Bearer $ROUTEWAY_MANAGEMENT_KEY"

    # Last 24 hours, specific model
    curl "https://api.routeway.ai/v1/account/analytics?period=24h&model=gpt-4o" \
      -H "Authorization: Bearer $ROUTEWAY_MANAGEMENT_KEY"
    ```
  </Tab>
</Tabs>

<Info>
  The `X-Cache` response header tells you whether the result was served from cache (`HIT`) or freshly computed (`MISS`). Analytics are cached for 5 minutes, so rapid repeated calls will return the same data without extra processing.
</Info>

***

## Rate Limits

You can find more information about rate limits [here](/account-management/overview).

***

## Common Use Cases

<CardGroup cols={2}>
  <Card title="Low-balance alerts" icon="bell">
    Poll `/v1/account/balance` every few minutes and send a Slack/email alert when balance drops below a threshold.
  </Card>

  <Card title="Cost attribution" icon="receipt">
    Use `/v1/account/activity` to break down costs by model and time period for internal billing or chargeback.
  </Card>

  <Card title="Usage dashboards" icon="layout-dashboard">
    Feed `/v1/account/analytics` into Grafana, Datadog, or a custom dashboard to visualize trends.
  </Card>

  <Card title="Budget automation" icon="shield-check">
    Combine balance checks with key management to auto-disable keys when a budget threshold is reached.
  </Card>
</CardGroup>
