> ## 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.
</Note>

* 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](/docs/en/api-reference/account/token-balance) endpoint, which only returns the aggregate balance of one key.

## Authorizations

<ParamField header="Authorization" type="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.
</ParamField>

<ParamField header="X-User-Id" type="string" required>
  Your numeric user ID. Required alongside the access token.
</ParamField>

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

<ParamField query="start_timestamp" type="integer" required>
  Start of the time window, Unix timestamp in seconds (inclusive).
</ParamField>

<ParamField query="end_timestamp" type="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.
</ParamField>

<ParamField query="token_id" type="integer">
  Optional. Restrict results to a single API Key by its numeric token ID. Omit to include all keys.
</ParamField>

<ParamField query="page_size" type="integer" default="50">
  Number of rows per page, `1`–`100`.
</ParamField>

<ParamField query="cursor" type="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.
</ParamField>

## Response

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

<ResponseField name="log_id" type="integer">
  Internal log ID of the request. Unique within the response.
</ResponseField>

<ResponseField name="created_at" type="integer">
  When the request was billed, Unix timestamp in seconds.
</ResponseField>

<ResponseField name="token_id" type="integer">
  ID of the API Key that made the request.
</ResponseField>

<ResponseField name="token_name" type="string">
  Name of the API Key.
</ResponseField>

<ResponseField name="model_name" type="string">
  Model that served the request.
</ResponseField>

<ResponseField name="task_id" type="string">
  Task ID for asynchronous requests (image/video generation). Empty for synchronous requests.
</ResponseField>

<ResponseField name="prompt_tokens" type="integer">
  Input tokens billed.
</ResponseField>

<ResponseField name="completion_tokens" type="integer">
  Output tokens billed.
</ResponseField>

<ResponseField name="cache_tokens" type="integer | null">
  Cached input tokens read (cache hits). `null` when the upstream did not report cache usage.
</ResponseField>

<ResponseField name="cache_creation_tokens" type="integer | null">
  Tokens written to cache. `null` when not reported.
</ResponseField>

<ResponseField name="reported_total_tokens" type="integer | null">
  Total tokens as reported by the upstream provider, when available.
</ResponseField>

<ResponseField name="total_tokens" type="integer">
  `prompt_tokens + completion_tokens`.
</ResponseField>

<ResponseField name="billing_phase" type="string">
  `pre_consumed`, `settled`, or `unknown` when the log predates detailed billing metadata.
</ResponseField>

<ResponseField name="quota" type="integer">
  Quota consumed, in the platform's internal unit.
</ResponseField>

<ResponseField name="cost_usd" type="string">
  Cost in USD, converted as `quota / quota_per_usd` (see `meta`). Returned as a string to preserve precision.
</ResponseField>

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

<ResponseField name="token_id" type="integer">
  API Key ID.
</ResponseField>

<ResponseField name="request_count" type="integer">
  Number of billable requests in the window.
</ResponseField>

<ResponseField name="prompt_tokens" type="integer">
  Total input tokens for this key.
</ResponseField>

<ResponseField name="completion_tokens" type="integer">
  Total output tokens for this key.
</ResponseField>

<ResponseField name="total_tokens" type="integer">
  `prompt_tokens + completion_tokens`.
</ResponseField>

<ResponseField name="quota" type="integer">
  Total quota consumed by this key.
</ResponseField>

<ResponseField name="cost_usd" type="string">
  Total cost in USD for this key.
</ResponseField>

### Meta

<ResponseField name="meta.has_more" type="boolean">
  Whether another page exists.
</ResponseField>

<ResponseField name="meta.next_cursor" type="string">
  Pass as `cursor` to fetch the next page. Empty when `has_more` is `false`.
</ResponseField>

<ResponseField name="meta.quota_per_usd" type="string">
  Internal quota units per USD used for the `cost_usd` conversion.
</ResponseField>

<ResponseField name="meta.consume_logging_enabled" type="boolean">
  Whether consumption logging is enabled. When `false`, responses may be empty.
</ResponseField>

<ResponseField name="meta.refunds_included" type="boolean">
  Currently always `false` — refunded amounts are not deducted.
</ResponseField>

<RequestExample>
  ```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']
  ```
</RequestExample>

<ResponseExample>
  ```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"
    }
  }
  ```
</ResponseExample>

## 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.