# Create an API key

Create an API key. Fields and permissions follow this gateway implementation.

## Endpoint and authentication

`POST https://business.tu-zi.com/api/token/`

Transport: json

- Use an account system token and New-Api-User (account ID), or a valid site login session.
- Manage system tokens in account settings. Inference API keys are not substitutes; keep system tokens out of frontend code.

Authorized OAuth access tokens are also supported; required scope: `token:write`

```http
Authorization: Bearer YOUR_SYSTEM_TOKEN
New-Api-User: YOUR_USER_ID
Content-Type: application/json
```

## Body parameters

| Field | Type | Required | Description / constraints |
| --- | --- | --- | --- |
| name | string | No | Name, up to 50 bytes. Example: demo |
| expired_time | integer | No | Unix seconds; -1 means no expiry. Set explicitly. Example: -1 |
| remain_quota | integer | No | Initial quota, nonnegative. Example: 1000 |
| unlimited_quota | boolean | No | Unlimited quota. Example: false |
| remain_count | integer | No | Request-count limit; 0 means unlimited. Example: 0 |
| group | string | No | Authorized groups, comma separated. Example:  |
| model_limits_enabled | boolean | No | Enable model restrictions. Example: false |
| model_limits | string | No | Comma-separated model IDs. Example:  |
| allow_ips | string | No | Allowed IP/CIDR, one per line. Example:  |
| exclude_ips | string | No | Blocked IP/CIDR, one per line. Example:  |
| cross_group_retry | boolean | No | Cross-group retry setting. Example: false |
| routing_preference | string | No | price or quality. Example: price |
| routing_quality_threshold | integer | No | 30, 40, 50, 60, 70, 80, 85, 90, 95. Example: 70 |
| mj_mode | string | No | Midjourney mode; omitted uses site default. Example: 默认 |
| rate_limits_enabled | boolean | No | Enable token rate limits. Example: false |
| rate_limits_time | integer | No | Rate-limit window in seconds; effective when enabled and both time and count are positive. Example: 0 |
| rate_limits_count | integer | No | Rate-limit request count. Example: 0 |
| rate_limits_content | string | No | Message returned when the token rate limit is reached; empty uses the default message. Example:  |

## Before calling

- Examples use this site's address. For another gateway, replace only the site address and keep the full endpoint path.
- Python / JavaScript read `SYSTEM_TOKEN` (account system token) and `USER_ID` (account ID) from the environment. In cURL, replace `YOUR_SYSTEM_TOKEN` and `YOUR_USER_ID`.

## Constraints

- Creation has side effects; do not retry automatically.
- Limits and allowed groups depend on the site/account.
- The example creates a quota-limited key.

## Minimal request example

```json
{
  "name": "demo",
  "expired_time": -1,
  "remain_quota": 1000,
  "unlimited_quota": false,
  "group": ""
}
```

## 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 POST 'https://business.tu-zi.com/api/token/' \
  --header 'Authorization: Bearer YOUR_SYSTEM_TOKEN' \
  --header 'New-Api-User: YOUR_USER_ID' \
  --header 'Content-Type: application/json' \
  --data '{
  "name": "demo",
  "expired_time": -1,
  "remain_quota": 1000,
  "unlimited_quota": false,
  "group": ""
}'
```

### python

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

url = "https://business.tu-zi.com/api/token/"
headers = json.loads("{\"Authorization\":\"Bearer YOUR_SYSTEM_TOKEN\",\"New-Api-User\":\"YOUR_USER_ID\",\"Content-Type\":\"application/json\"}")
for name in ["SYSTEM_TOKEN","USER_ID"]:
    if not os.environ.get(name, "").strip():
        raise RuntimeError("Set environment variable: " + name)
headers["Authorization"] = "Bearer " + os.environ["SYSTEM_TOKEN"]
headers["New-Api-User"] = os.environ["USER_ID"]
payload = json.loads("{\"name\":\"demo\",\"expired_time\":-1,\"remain_quota\":1000,\"unlimited_quota\":false,\"group\":\"\"}")
response = requests.request("POST", url, headers=headers, json=payload, 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://business.tu-zi.com/api/token/";
const headers = {
  "Authorization": "Bearer YOUR_SYSTEM_TOKEN",
  "New-Api-User": "YOUR_USER_ID",
  "Content-Type": "application/json"
};
for (const name of ["SYSTEM_TOKEN","USER_ID"]) {
  if (!process.env[name]?.trim()) throw new Error("Set environment variable: " + name);
}
headers.Authorization = 'Bearer ' + process.env.SYSTEM_TOKEN;
headers['New-Api-User'] = process.env.USER_ID;
const response = await fetch(url, { method: "POST", headers, body: JSON.stringify({
  "name": "demo",
  "expired_time": -1,
  "remain_quota": 1000,
  "unlimited_quota": false,
  "group": ""
}), 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 |
| --- | --- | --- |
| success | boolean | Business success; do not rely only on HTTP status. |
| message | string | Result or error message. |
| data.id | integer | New token ID. |
| data.key | string | Full key; store securely. |

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

```json
{
  "success": true,
  "message": "",
  "data": {
    "id": 123,
    "key": "YOUR_NEW_KEY"
  }
}
```

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

- Require success=true and inspect data. Read configuration back through its retrieval endpoint after changing it.
- Empty lists may be valid but do not prove a specific resource exists.

## Errors and retries

Check HTTP status and success. HTTP 200 alone does not guarantee success.

- **Business validation:** errors may return HTTP 200 with `{"success":false,"message":"..."}`; some include `error.code`.
- **Authentication failures:** may return 401/403.
- **Rate limiting:** may return 429.

- 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-10

Source: https://business.tu-zi.com/en/docs/api/reference-token-create

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