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

# Balance Query API

> Query LaoZhang API account quota, used_quota, request_count, and user group with a system AccessToken for monitoring, balance alerts, and billing diagnostics.

## Overview

The Balance Query API returns the current account quota, used quota, request count, and account group. Use it for backend monitoring, low-balance alerts, billing diagnostics, and internal operations dashboards.

<Info>
  This endpoint uses a system AccessToken, not the regular API key used for model calls. The AccessToken has broader account permissions, so keep it on the server side and store it in environment variables or a secrets manager.
</Info>

## Get Authorization

<Steps>
  <Step title="Open account settings">
    Log in to the [LaoZhang API console](https://api.laozhang.ai/account/profile) and open account settings.
  </Step>

  <Step title="Open system token">
    Select "System Token" and complete the password verification flow shown in the console.
  </Step>

  <Step title="Save the AccessToken">
    Copy the token immediately after it is generated. Creating a new token may invalidate the previous token.
  </Step>
</Steps>

<Warning>
  Do not expose the full AccessToken in source code, browser apps, logs, screenshots, or support tickets. For support diagnostics, provide the request time, HTTP status code, response message, and a redacted command only.
</Warning>

## Endpoint

| Item               | Value                                    |
| ------------------ | ---------------------------------------- |
| Endpoint URL       | `https://api.laozhang.ai/api/user/self`  |
| Method             | `GET`                                    |
| Authentication     | `Authorization` header                   |
| Request parameters | None                                     |
| Response format    | JSON; add `--compressed` when using cURL |

## Request

### Headers

| Header          | Required | Description                                             |
| --------------- | -------- | ------------------------------------------------------- |
| `Authorization` | Yes      | System AccessToken, passed directly as the header value |
| `Accept`        | No       | Recommended: `application/json`                         |
| `Content-Type`  | No       | Recommended: `application/json`                         |

### Parameters

This endpoint does not require query parameters or a request body. Keep alert thresholds, business labels, and notification channels in your monitoring configuration rather than in the endpoint URL.

## Response

### Successful Response

```json theme={null}
{
  "success": true,
  "message": null,
  "data": {
    "id": 19489,
    "username": "demo_user",
    "display_name": "demo_user",
    "role": 1,
    "status": 1,
    "email": "",
    "quota": 24997909,
    "used_quota": 10027091,
    "request_count": 339,
    "group": "svip",
    "ModelFixedPrice": []
  }
}
```

### Core Fields

| Field                  | Type          | Description                                                   |
| ---------------------- | ------------- | ------------------------------------------------------------- |
| `success`              | Boolean       | Whether the request succeeded                                 |
| `message`              | String / null | Error message; usually `null` on success                      |
| `data.username`        | String        | Username                                                      |
| `data.display_name`    | String        | Display name                                                  |
| `data.quota`           | Integer       | Current remaining quota, suitable for alert thresholds        |
| `data.used_quota`      | Integer       | Used quota                                                    |
| `data.request_count`   | Integer       | Total request count                                           |
| `data.group`           | String        | Current account group                                         |
| `data.ModelFixedPrice` | Array         | Model pricing list; can be ignored when only checking balance |
| `data.access_token`    | String        | Sensitive field; do not write it to normal logs if returned   |

<Tip>
  The response may include additional fields depending on the account state. Depend only on the fields your integration needs, and allow unknown fields so your parser does not fail when the response expands.
</Tip>

## Quota And Balance Calculation

The `quota` field is returned in quota units, not directly in USD. Use this conversion for balance display:

| Item                    | Formula                       | Example                                                  |
| ----------------------- | ----------------------------- | -------------------------------------------------------- |
| Remaining USD balance   | `quota ÷ 500K`                | `24997909 ÷ 500K = 49.995818`, approximately `50.00 USD` |
| Used USD amount         | `used_quota ÷ 500K`           | `10027091 ÷ 500K = 20.054182`, approximately `20.05 USD` |
| Historical total amount | `(quota + used_quota) ÷ 500K` | Approximately `70.05 USD` in the sample response         |

In other words, `500K` quota is approximately `1 USD`. If the API returns `quota: 24997909`, the current available balance is approximately `50.00 USD`.

<Tip>
  Use this formula for balance display. Actual model charges still depend on current model pricing, account group, usage logs, and console display. For production alerts, store both the raw `quota` value and the converted USD amount so diagnostics keep full precision.
</Tip>

## Code Examples

<Tabs>
  <Tab title="cURL">
    ```bash theme={null}
    export LAOZHANG_ACCESS_TOKEN='YOUR_ACCESS_TOKEN'

    curl --compressed -s 'https://api.laozhang.ai/api/user/self' \
      -H 'Accept: application/json' \
      -H "Authorization: ${LAOZHANG_ACCESS_TOKEN}" \
      -H 'Content-Type: application/json'
    ```

    `--compressed` tells cURL to decompress gzip responses. Without it, the terminal may show garbled output and `jq` may report `Invalid numeric literal`.
  </Tab>

  <Tab title="jq Extract">
    ```bash theme={null}
    export LAOZHANG_ACCESS_TOKEN='YOUR_ACCESS_TOKEN'

    curl --compressed -s 'https://api.laozhang.ai/api/user/self' \
      -H 'Accept: application/json' \
      -H "Authorization: ${LAOZHANG_ACCESS_TOKEN}" \
      -H 'Content-Type: application/json' | \
      jq '.data | {
        quota,
        remaining_usd: (.quota / (50 * 10000)),
        used_quota,
        used_usd: (.used_quota / (50 * 10000)),
        request_count,
        group
      }'
    ```
  </Tab>

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

    token = os.environ["LAOZHANG_ACCESS_TOKEN"]
    response = requests.get(
        "https://api.laozhang.ai/api/user/self",
        headers={
            "Accept": "application/json",
            "Authorization": token,
            "Content-Type": "application/json",
        },
        timeout=10,
    )
    response.raise_for_status()

    payload = response.json()
    account = payload["data"]
    quota_unit_per_usd = 50 * 10000

    print("quota:", account["quota"])
    print("remaining_usd:", round(account["quota"] / quota_unit_per_usd, 2))
    print("used_quota:", account["used_quota"])
    print("used_usd:", round(account["used_quota"] / quota_unit_per_usd, 2))
    print("request_count:", account["request_count"])
    print("group:", account.get("group"))
    ```

    Python `requests` handles gzip decompression automatically.
  </Tab>

  <Tab title="Node.js">
    ```javascript theme={null}
    const token = process.env.LAOZHANG_ACCESS_TOKEN;

    const response = await fetch("https://api.laozhang.ai/api/user/self", {
      method: "GET",
      headers: {
        Accept: "application/json",
        Authorization: token,
        "Content-Type": "application/json",
      },
    });

    if (!response.ok) {
      throw new Error(`Balance query failed: HTTP ${response.status}`);
    }

    const payload = await response.json();
    const account = payload.data;
    const quotaUnitPerUsd = 50 * 10000;

    console.log({
      quota: account.quota,
      remaining_usd: Number((account.quota / quotaUnitPerUsd).toFixed(2)),
      used_quota: account.used_quota,
      used_usd: Number((account.used_quota / quotaUnitPerUsd).toFixed(2)),
      request_count: account.request_count,
      group: account.group,
    });
    ```
  </Tab>
</Tabs>

## Error Responses

### HTTP 401 - Authentication Failed

```json theme={null}
{
  "success": false,
  "message": "Unauthorized"
}
```

Common causes include an empty `Authorization` header, an incomplete token, an expired token, or using a regular API key instead of the system AccessToken.

### HTTP 403 - Permission Denied

```json theme={null}
{
  "success": false,
  "message": "Forbidden"
}
```

Common causes include insufficient token permissions or an account state that needs support confirmation.

### Garbled Response Or jq Error

If cURL returns garbled output or `jq` reports `Invalid numeric literal`, the gzip response was likely not decompressed. Add `--compressed`.

## Monitoring Recommendations

* Store `LAOZHANG_ACCESS_TOKEN` in environment variables or a secrets manager
* Set a reasonable timeout, such as 10 seconds
* Avoid high-frequency polling; balance monitoring usually does not need second-level checks
* Include `quota`, converted `remaining_usd`, `used_quota`, `request_count`, request time, and HTTP status in alerts
* Do not log the full `Authorization`, `access_token`, or sensitive account fields

## Related Docs

* For the FAQ version, see [How to Query Account Balance via API](/en/faq/balance-query-api)
* If requests fail even with remaining quota, see [Insufficient Balance](/en/faq/balance-insufficient)
* To inspect per-request model, token, and billing records, see [Usage Logs](/en/faq/call-logs)
