# Legacy usage lookup by key

Legacy usage lookup by key; the contract below follows this gateway implementation.

## Endpoint and authentication

`GET https://api.tu-zi.com/api/token/key/{key}`

Transport: json

- Legacy lookup: put the inference API key in the path and its owner's account ID in New-Api-User (Rix-Api-User is also accepted).
- No additional Authorization is required. Key and owner must match.
- URLs contain credentials; redact access logs. Prefer Bearer-authenticated /api/usage/token/ for new integrations.

```http
New-Api-User: YOUR_USER_ID
```

## Path parameters

| Field | Type | Required | Description / constraints |
| --- | --- | --- | --- |
| key | string | Yes | Inference API key, optionally prefixed with sk-. Example: YOUR_KEY |

## Before calling

- Examples use this site's address. For another gateway, replace only the site address and keep the full endpoint path.
- Set `API_KEY` and `USER_ID` in the environment. In cURL, replace `YOUR_USER_ID` with the key owner's account ID.

## Constraints

- Values are raw quota; use site conversion settings instead of hard-coded currency/rates.
- Missing/mismatched owner or invalid key returns 401; empty input can return success=false.
- This lookup does not create or recover keys.

## Code examples

### curl

```bash
# Requires curl 7.76+. HTTP errors exit nonzero; inspect JSON/SSE business status too.
curl --fail-with-body --silent --show-error --connect-timeout 10 --max-time 120 --request GET 'https://api.tu-zi.com/api/token/key/'"${API_KEY}"'' \
  --header 'New-Api-User: YOUR_USER_ID'
```

### python

```python
# Install dependency: python3 -m pip install requests
import json
import os
import requests

url = "https://api.tu-zi.com/api/token/key/YOUR_KEY"
headers = json.loads("{\"New-Api-User\":\"YOUR_USER_ID\"}")
for name in ["API_KEY","USER_ID"]:
    if not os.environ.get(name, "").strip():
        raise RuntimeError("Set environment variable: " + name)
headers["New-Api-User"] = os.environ["USER_ID"]
from urllib.parse import quote
url = url.replace("YOUR_KEY", quote(os.environ["API_KEY"], safe=""))
response = requests.request("GET", url, headers=headers, timeout=120)
response.raise_for_status()
result = response.json()
if isinstance(result, dict) and (result.get("success") is False or result.get("code") is False or result.get("error")):
    raise RuntimeError(json.dumps(result, ensure_ascii=False))
print(json.dumps(result, ensure_ascii=False, indent=2))
```

### javascript

```javascript
// Run with Node.js 20+; save as example.mjs.
const url = "https://api.tu-zi.com/api/token/key/YOUR_KEY".replace("YOUR_KEY", encodeURIComponent(process.env.API_KEY));
const headers = {
  "New-Api-User": "YOUR_USER_ID"
};
for (const name of ["API_KEY","USER_ID"]) {
  if (!process.env[name]?.trim()) throw new Error("Set environment variable: " + name);
}
headers['New-Api-User'] = process.env.USER_ID;
const response = await fetch(url, { method: "GET", headers, signal: AbortSignal.timeout(120000) });
if (!response.ok) throw new Error(await response.text());
const result = await response.json();
if (result?.success === false || result?.code === false || result?.error) throw new Error(JSON.stringify(result));
console.log(JSON.stringify(result, null, 2));
```

## Response fields

| Field | Type | Description / constraints |
| --- | --- | --- |
| code | boolean | True on success. |
| data.object | string | Always token_usage. |
| data.name | string | Token name. |
| data.total_granted | integer | remain_quota + used_quota in raw quota units. |
| data.total_used | integer | Used quota. |
| data.total_available | integer | Remaining quota. |
| data.unlimited_quota | boolean | Whether quota is unlimited. |
| data.expires_at | integer | Unix seconds; 0 means no expiry. |
| data.model_limits | object | Model restriction set. |
| data.model_limits_enabled | boolean | Whether model restrictions are enabled. |

Illustrative response; some endpoints show essential fields only. Optional fields may be absent.

```json
{
  "code": true,
  "message": "ok",
  "data": {
    "object": "token_usage",
    "total_granted": 1000000,
    "total_used": 500000,
    "total_available": 500000,
    "unlimited_quota": false,
    "expires_at": 0,
    "name": "Example token",
    "model_limits": {},
    "model_limits_enabled": false
  }
}
```

## Confirming success

Check HTTP status, the business status in the body and the required result fields. Do not rely only on HTTP 200 or the script exit code.

## Errors and retries

Check HTTP status and protocol-specific errors; do not mix error formats across protocols.

- **401/403:** check credentials and permissions.
- **429:** classify temporary throttling, exhausted quota, or service capacity failure; only transient failures merit bounded backoff.
- **5xx:** inspect the gateway, upstream, and model/channel configuration.

Error bodies may contain error/message/code depending on the protocol.

- Use bounded exponential backoff for reads encountering transient errors; fix parameter, authentication, quota, or configuration failures first.
- Do not blindly retry task creation, generation, or key mutations, to avoid duplicate billing or execution.

## Documentation source

Definition version: 1

Reviewed: 2026-11-08

Source: https://api.tu-zi.com/en/docs/api/reference-token-lookup-by-key

Related protocol guide: https://api.tu-zi.com/docs/api/api-compatibility

This export contains documentation and examples only, without real credentials, account data or user requests.
