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

# Query Token Usage

> Query per-request token consumption and cost across all of your API Keys

> [!NOTE]
>
> **Note for users in mainland China:** Please use `https://toapis.cn` as the API endpoint (Base URL). Replace `https://toapis.com` with `https://toapis.cn` in the examples in this document.

* Query per-request token consumption and cost across **all** of your API Keys, or filter to a single key
* Input, output and cached token counts reported separately
* Aggregated per-key totals via the summary endpoint
* Cursor-based pagination, time window up to 31 days

These endpoints read your billing logs and return every billable request with its token breakdown and cost, plus a per-key rollup. They complement the [Query Token Balance](https://docs.toapis.com/docs/en/api-reference/account/token-balance.md) endpoint, which only returns the aggregate balance of one key.

## Authorizations

**Authorization** `string` *required*

These endpoints authenticate as your **user account**, not as an API Key.

1. Open [Account Settings](https://toapis.com/dashboard/settings) and click **Generate Token** under "System Access Token" to create an access token (not an `sk-` API key). Generating again invalidates the previous token.
2. Send it in the `Authorization` header together with your user ID:

```
Authorization: Bearer YOUR_ACCESS_TOKEN
X-User-Id: YOUR_USER_ID
```

Your numeric user ID is shown on the same settings page.

**X-User-Id** `string` *required*

Your numeric user ID. Required alongside the access token.

## Endpoints

```
GET /api/usage/tokens/requests   # per-request detail
GET /api/usage/tokens/summary    # per-key aggregate
```

## Query Parameters

Both endpoints accept the same parameters. Unknown or repeated parameters are rejected with `422`.

**start\_timestamp** `integer` *required*

Start of the time window, Unix timestamp in seconds (inclusive).

**end\_timestamp** `integer` *required*

End of the time window, Unix timestamp in seconds (exclusive). Must be after `start_timestamp`; the window may span at most 31 days.

**token\_id** `integer`

Optional. Restrict results to a single API Key by its numeric token ID. Omit to include all keys.

**page\_size** `integer` (default: 50)

Number of rows per page, `1`–`100`.

**cursor** `string`

Pagination cursor returned as `meta.next_cursor` by the previous response. Only valid for the same endpoint, time window and `token_id` filter that produced it.

## Response

`GET /api/usage/tokens/requests` returns one row per billable request, newest first.

**log\_id** `integer`

Internal log ID of the request. Unique within the response.

**created\_at** `integer`

When the request was billed, Unix timestamp in seconds.

**token\_id** `integer`

ID of the API Key that made the request.

**token\_name** `string`

Name of the API Key.

**model\_name** `string`

Model that served the request.

**task\_id** `string`

Task ID for asynchronous requests (image/video generation). Empty for synchronous requests.

**prompt\_tokens** `integer`

Input tokens billed.

**completion\_tokens** `integer`

Output tokens billed.

**cache\_tokens** `integer | null`

Cached input tokens read (cache hits). `null` when the upstream did not report cache usage.

**cache\_creation\_tokens** `integer | null`

Tokens written to cache. `null` when not reported.

**reported\_total\_tokens** `integer | null`

Total tokens as reported by the upstream provider, when available.

**total\_tokens** `integer`

`prompt_tokens + completion_tokens`.

**billing\_phase** `string`

`pre_consumed`, `settled`, or `unknown` when the log predates detailed billing metadata.

**quota** `integer`

Quota consumed, in the platform's internal unit.

**cost\_usd** `string`

Cost in USD, converted as `quota / quota_per_usd` (see `meta`). Returned as a string to preserve precision.

`GET /api/usage/tokens/summary` returns one row per API Key, ordered by `token_id`.

**token\_id** `integer`

API Key ID.

**request\_count** `integer`

Number of billable requests in the window.

**prompt\_tokens** `integer`

Total input tokens for this key.

**completion\_tokens** `integer`

Total output tokens for this key.

**total\_tokens** `integer`

`prompt_tokens + completion_tokens`.

**quota** `integer`

Total quota consumed by this key.

**cost\_usd** `string`

Total cost in USD for this key.

### Meta

**meta.has\_more** `boolean`

Whether another page exists.

**meta.next\_cursor** `string`

Pass as `cursor` to fetch the next page. Empty when `has_more` is `false`.

**meta.quota\_per\_usd** `string`

Internal quota units per USD used for the `cost_usd` conversion.

**meta.consume\_logging\_enabled** `boolean`

Whether consumption logging is enabled. When `false`, responses may be empty.

**meta.refunds\_included** `boolean`

Currently always `false` — refunded amounts are not deducted.

```bash cURL — requests theme={null}
curl --request GET \
  --url 'https://toapis.com/api/usage/tokens/requests?start_timestamp=1759708800&end_timestamp=1760313600&page_size=100' \
  --header 'Authorization: Bearer YOUR_ACCESS_TOKEN' \
  --header 'X-User-Id: YOUR_USER_ID'
```

```bash cURL — summary for one key theme={null}
curl --request GET \
  --url 'https://toapis.com/api/usage/tokens/summary?start_timestamp=1759708800&end_timestamp=1760313600&token_id=45' \
  --header 'Authorization: Bearer YOUR_ACCESS_TOKEN' \
  --header 'X-User-Id: YOUR_USER_ID'
```

```python Python — iterate all pages theme={null}
import requests

API_BASE = 'https://toapis.com'
headers = {
    'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
    'X-User-Id': 'YOUR_USER_ID',
}
params = {
    'start_timestamp': 1759708800,
    'end_timestamp': 1760313600,
    'page_size': 100,
}

while True:
    r = requests.get(f'{API_BASE}/api/usage/tokens/requests',
                     headers=headers, params=params)
    body = r.json()
    for row in body['data']:
        print(row['created_at'], row['token_name'], row['model_name'],
              row['prompt_tokens'], row['completion_tokens'],
              row['cache_tokens'], row['cost_usd'])
    if not body['meta']['has_more']:
        break
    params['cursor'] = body['meta']['next_cursor']
```

```json 200 - requests theme={null}
{
  "success": true,
  "data": [
    {
      "log_id": 10241024,
      "created_at": 1760001234,
      "token_id": 45,
      "token_name": "prod-backend",
      "model_name": "gpt-5.1",
      "task_id": "",
      "prompt_tokens": 148320,
      "completion_tokens": 2198,
      "cache_tokens": 96000,
      "cache_creation_tokens": 0,
      "reported_total_tokens": 150518,
      "total_tokens": 150518,
      "billing_phase": "settled",
      "quota": 7839,
      "cost_usd": "0.015678"
    }
  ],
  "meta": {
    "start_timestamp": 1759708800,
    "end_timestamp": 1760313600,
    "page_size": 100,
    "has_more": true,
    "next_cursor": "eyJraW5kIjoicmVxdWVzdHMiLC4uLn0",
    "cost_basis": "consume_log_quota",
    "currency": "USD",
    "quota_per_usd": "500000",
    "consume_logging_enabled": true,
    "refunds_included": false,
    "total_tokens_basis": "logged_prompt_plus_completion"
  }
}
```

```json 200 - summary theme={null}
{
  "success": true,
  "data": [
    {
      "token_id": 45,
      "request_count": 87,
      "prompt_tokens": 3200400,
      "completion_tokens": 150220,
      "total_tokens": 3350620,
      "quota": 401234,
      "cost_usd": "0.802468"
    }
  ],
  "meta": {
    "start_timestamp": 1759708800,
    "end_timestamp": 1760313600,
    "page_size": 50,
    "has_more": false,
    "next_cursor": "",
    "cost_basis": "consume_log_quota",
    "currency": "USD",
    "quota_per_usd": "500000",
    "consume_logging_enabled": true,
    "refunds_included": false,
    "total_tokens_basis": "logged_prompt_plus_completion"
  }
}
```

```json 401 theme={null}
{
  "success": false,
  "error": {
    "code": "unauthorized",
    "message": "user authentication is required"
  }
}
```

```json 422 theme={null}
{
  "success": false,
  "error": {
    "code": "invalid_query",
    "message": "time range must be positive and no longer than 31 days"
  }
}
```

```json 503 theme={null}
{
  "success": false,
  "error": {
    "code": "query_timeout",
    "message": "usage query exceeded the time limit; use a shorter time range"
  }
}
```

## Notes

* Only **billable** requests are listed. Failed requests that were not billed do not appear, and no per-request success flag is returned.
* Cost reflects the quota recorded at billing time; it is not re-priced against the current catalog, and refunds are not deducted.
* Raw API keys, channel, IP addresses and request/response content are never exposed by these endpoints.
* `cursor` is bound to the endpoint, time window and `token_id` filter — do not reuse a cursor across different queries.
* Queries time out after a few seconds; if you receive `query_timeout`, shorten the time window and retry.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.