# Token Management (System Advanced API)

Once the site enables the **"Site Advanced API"** plugin in the admin console, you can create an **Account Permission Key** (`tb_acct_...`) in Console **Settings -> Below Notifications -> Advanced API**, and programmatically manage your API tokens via the open endpoints below (query masked lists and details, create new tokens, update quota/expiration/model and IP restrictions, toggle active status, reset used quota, and delete tokens).

> [!IMPORTANT]
> - **Security Tips**: Enable two-factor authentication (2FA), and configure IP whitelists and expiration times for your key (`tb_acct_...`); the plaintext key is shown only once upon creation—never expose it in frontend code.
> - **Masking Protection**: `token_key` returned by query, update, toggle, and reset endpoints is always masked with asterisks (e.g., `sk-aB12****xy9Z`). Retrieving the plaintext of existing keys is not supported.
> - **Time Format**: Time fields are uniformly output in the **site operational timezone** (e.g., `2026-11-15 01:08:26 (UTC+8)`; visibility of the timezone suffix depends on site configuration).
> - **Concurrency Control**: When "API Call Security" is enabled, maximum concurrency is tiered based on available account funds; exceeding the limit returns HTTP `429`.

---

### 1. Base URL & Authentication

* **Base URL**: `https://www.tokenpad.ai/api/open/v1`
* **Authentication Header (Choose One)**:

```http
Authorization: Bearer tb_acct_your_account_key
```

Or:

```http
X-Account-Api-Key: tb_acct_your_account_key
```

---

### 2. List API Tokens (Masked)

Retrieve the list of personal API keys under the current account. Every record's `token_key` is strictly returned as a masked string preserving only the prefix and suffix with asterisks in the middle.

* **Path**: `GET /api/open/v1/tokens`
* **Query Parameters (Query)**:

| Parameter | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| `include_playground_2026` | `integer` | `0` | Whether to include Playground / system-reserved keys (`1` include, `0` exclude) |
| `is_active` | `integer` | All | Filter by status: `1` enabled only, `0` disabled only |
| `keyword` | `string` | None | Fuzzy filter by key name or `kid` keyword |

* **Request Example (Curl)**:

```bash
curl -s "https://www.tokenpad.ai/api/open/v1/tokens?is_active=1" \
  -H "Authorization: Bearer tb_acct_your_account_key"
```

* **Response Example**:

```json
{
  "data": [
    {
      "id": 42,
      "name": "production-app",
      "token_key": "sk-9xA2****kP8Q",
      "kid": "usr82f1a9c0",
      "quota_limit": 500.0,
      "used_quota": 12.45,
      "daily_quota_limit": 50.0,
      "daily_used_quota": 1.8,
      "weekly_quota_limit": null,
      "weekly_used_quota": 6.2,
      "monthly_quota_limit": 200.0,
      "monthly_used_quota": 12.45,
      "usage_limit": 10000,
      "usage_count": 318,
      "rps_limit": 10,
      "rpm_limit": 300,
      "allowed_models": "[\"gpt-4o\",\"claude-sonnet-4-6\"]",
      "allowed_ips": "192.168.1.0/24",
      "high_availability": 0,
      "is_active": 1,
      "expires_at": "2026-12-31 23:59:59 (UTC+8)",
      "created_at": "2026-11-10 16:00:00 (UTC+8)"
    }
  ],
  "total": 1
}
```

---

### 3. Get Single Token Details (Masked)

Query the configuration and daily/weekly/monthly/total usage statistics of the key with the specified `id`. The returned `token_key` remains masked.

* **Path**: `GET /api/open/v1/tokens/{id}`
* **Request Example (Curl)**:

```bash
curl -s "https://www.tokenpad.ai/api/open/v1/tokens/42" \
  -H "Authorization: Bearer tb_acct_your_account_key"
```

---

### 4. Create New Token

Create a personal API key with full parity to the console page, supporting total quota, daily/weekly/monthly periodic quotas, call count limits, RPS/RPM rate limits, model whitelists, IP whitelists, and expiration configuration.

* **Path**: `POST /api/open/v1/tokens`
* **Request Body Parameters (JSON)**:

| Parameter | Type | Required | Description |
| :--- | :--- | :--- | :--- |
| `name` | `string` | No | Key name (auto-generated by default) |
| `quota_limit` | `number \| null` | No | Total spending quota limit (in site billing units); `null` or omitted means unlimited |
| `daily_quota_limit` | `number \| null` | No | Daily spending quota limit |
| `weekly_quota_limit` | `number \| null` | No | Weekly spending quota limit |
| `monthly_quota_limit` | `number \| null` | No | Monthly spending quota limit |
| `usage_limit` | `integer \| null` | No | Total call count limit |
| `rps_limit` | `integer \| null` | No | Requests per second limit (RPS) |
| `rpm_limit` | `integer \| null` | No | Requests per minute limit (RPM) |
| `allowed_models` | `string[] \| null` | No | List of allowed model IDs; empty or `null` means unrestricted |
| `allowed_ips` | `string \| null` | No | Allowed source IPs / CIDRs (comma-separated) |
| `expires_at` | `string \| null` | No | Absolute expiration time (supports site timezone `YYYY-MM-DD HH:mm:ss`, `YYYY-MM-DD`, or ISO 8601); pass `""` for never expires |
| `expire_days` | `integer` | No | Validity days relative to the current time (e.g., `30` means expires in 30 days; cannot be combined with `expires_at`) |
| `high_availability` | `integer` | No | High-availability mode toggle: `0` off (default), `1` on |
| `is_active` | `integer` | No | Initial status: `1` enabled (default), `0` disabled |

* **Request Example (Curl)**:

```bash
curl -s -X POST "https://www.tokenpad.ai/api/open/v1/tokens" \
  -H "Authorization: Bearer tb_acct_your_account_key" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "backend-worker-01",
    "quota_limit": 200.0,
    "daily_quota_limit": 25.0,
    "weekly_quota_limit": 100.0,
    "monthly_quota_limit": 200.0,
    "usage_limit": 5000,
    "rps_limit": 5,
    "rpm_limit": 120,
    "allowed_models": ["gpt-4o", "gemini-2.5-flash"],
    "allowed_ips": "203.0.113.10,10.0.0.0/8",
    "expire_days": 30,
    "is_active": 1
  }'
```

---

### 5. Update / Configure Existing Token

Update an existing key's name, quota limits, call count limit, RPS/RPM, expiration time, model whitelist, IP whitelist, and active status (only pass the fields you want to update; `token_key` in the response remains masked).

* **Path**: `PUT /api/open/v1/tokens/{id}` or `PATCH /api/open/v1/tokens/{id}`
* **Clearing Expiration**: To change an expiring key to **never expire**, pass `"expires_at": ""` or `"expires_at": null`.
* **Request Example (Curl)**:

```bash
curl -s -X PUT "https://www.tokenpad.ai/api/open/v1/tokens/42" \
  -H "Authorization: Bearer tb_acct_your_account_key" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "backend-worker-prod",
    "quota_limit": 1000.0,
    "daily_quota_limit": 80.0,
    "allowed_models": ["gpt-4o", "claude-sonnet-4-6"],
    "expires_at": "2027-06-30 23:59:59"
  }'
```

---

### 6. Quick Toggle Token Status

Quickly enable or disable a specified key without submitting the full configuration.

* **Path**: `PATCH /api/open/v1/tokens/{id}/status` or `POST /api/open/v1/tokens/{id}/status`
* **Request Body Parameters**: Pass `{ "is_active": 0 | 1 }` or `{ "enabled": true | false }`.
* **Request Example (Curl)**:

```bash
curl -s -X PATCH "https://www.tokenpad.ai/api/open/v1/tokens/42/status" \
  -H "Authorization: Bearer tb_acct_your_account_key" \
  -H "Content-Type: application/json" \
  -d '{"is_active": 0}'
```

---

### 7. Reset Token Used Quota / Usage Count

Reset the consumed quota or call count of a key along a specified dimension (does not affect your actual account wallet ledger; only resets that token's limit counters).

* **Path**: `POST /api/open/v1/tokens/{id}/reset-usage`
* **Supported Targets (`target`)**: `all` (default, reset all), `total`, `daily`, `weekly`, `monthly`, `usage_count`.
* **Request Example (Curl)**:

```bash
curl -s -X POST "https://www.tokenpad.ai/api/open/v1/tokens/42/reset-usage" \
  -H "Authorization: Bearer tb_acct_your_account_key" \
  -H "Content-Type: application/json" \
  -d '{"target": "daily"}'
```

---

### 8. Delete & Destroy Token

Permanently delete a specified personal key. Once destroyed, it immediately becomes unusable and cannot be recovered (except system-locked dedicated keys).

* **Path**: `DELETE /api/open/v1/tokens/{id}`
* **Request Example (Curl)**:

```bash
curl -s -X DELETE "https://www.tokenpad.ai/api/open/v1/tokens/42" \
  -H "Authorization: Bearer tb_acct_your_account_key"
```

* **Response Example**:

```json
{
  "message": "Token deleted successfully",
  "id": 42
}
```

---

### 9. List Available Models

Retrieve the list of model IDs visible to the current user and backed by available channels, making it convenient to populate `allowed_models` when creating or configuring keys.

* **Path**: `GET /api/open/v1/models`
* **Request Example (Curl)**:

```bash
curl -s "https://www.tokenpad.ai/api/open/v1/models" \
  -H "Authorization: Bearer tb_acct_your_account_key"
```
