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

# 建立 API key

> 使用 CometAPI POST /api/token/ 為已驗證的帳戶建立 API key。

使用此端點為自動化、內部儀表板或伺服器端整合建立 API key。

<Note>
  在 [Console → Personal Settings](https://www.cometapi.com/console/personal) 產生 personal access token，然後將它作為原始的 `Authorization` 標頭值傳送。不要加上 `Bearer` 前綴。
</Note>

<Warning>
  建立回應只會確認操作成功，不會包含新的 key 記錄或 key 值。建立完成後，請呼叫 [列出 API keys](./list-api-keys) 讀取最新的 key 記錄。
</Warning>

## 請求本文

| 欄位                     | 類型             | 說明                                                                                                                         |
| ---------------------- | -------------- | -------------------------------------------------------------------------------------------------------------------------- |
| `name`                 | string         | 使用者可讀的 key 顯示名稱。必須為 50 個字元以內。                                                                                              |
| `expired_time`         | integer        | key 到期時的 Unix 時間戳（秒）。使用 `-1` 表示永不過期。                                                                                       |
| `remain_quota`         | integer        | CometAPI 內部配額單位中的起始配額。如果此值降至 `0` 且 `unlimited_quota` 為 `false`，則使用此 key 的模型請求會因配額耗盡而遭到拒絕。                                  |
| `unlimited_quota`      | boolean        | 此 key 是否略過剩餘配額檢查。只有在即使 `remain_quota` 為 `0` 時，該 key 仍應繼續運作的情況下，才設為 `true`。                                                 |
| `model_limits_enabled` | boolean        | 是否將此 key 限制為只能使用特定模型。當為 `false` 時，會忽略 `model_limits`。                                                                      |
| `model_limits`         | string         | 當 `model_limits_enabled` 為 `true` 時，此 key 允許使用的 model ID，以逗號分隔。請使用 `/v1/models` 回傳的 model ID；若不限制模型，請使用空字串。                |
| `allow_ips`            | string or null | 選用的 IP 允許清單。請提供一個 JSON 字串，並以換行字元（`\n`）分隔各項目。每個項目可以是單一 IPv4 位址、單一 IPv6 位址、IPv4 CIDR 或 IPv6 CIDR。使用 `null` 或 `""` 可停用 IP 限制。 |
| `group`                | string         | 選用的帳戶群組限制。若沒有明確群組，請使用空字串。非空值必須是該帳戶可用的群組，否則 API 會回傳 `success: false`。                                                       |
| `cross_group_retry`    | boolean        | 是否啟用跨群組重試，以支援自動群組路由。只有當此 key 使用自動路由群組時，這個欄位才有意義。                                                                           |

## 允許清單格式

若要允許多個 IP 或 CIDR 範圍，請將它們作為單一 JSON 字串傳送，並在各項目之間使用 `\n`：

```json theme={null}
{
  "allow_ips": "198.51.100.10\n203.0.113.0/24\n2001:db8::/32"
}
```

此範例允許一個 IPv4 位址、一個 IPv4 CIDR 範圍，以及一個 IPv6 CIDR 範圍。


## OpenAPI

````yaml api/openapi/api-keys/create-api-key.openapi.json POST /api/token/
openapi: 3.1.0
info:
  title: Create API Key
  version: 1.0.0
servers:
  - url: https://api.cometapi.com
security:
  - accessTokenAuth: []
paths:
  /api/token/:
    post:
      summary: Create a new API key
      description: >-
        Create an API key for the authenticated account. The response confirms
        success but does not include the new key record or key value; call the
        list endpoint after creation to read the record.
      operationId: createApiKey
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateApiKeyRequest'
            examples:
              default:
                summary: Create an API key
                value:
                  name: production
                  expired_time: -1
                  remain_quota: 100000
                  unlimited_quota: false
                  model_limits_enabled: false
                  model_limits: ''
                  allow_ips: null
                  group: ''
                  cross_group_retry: false
              with_ip_allowlist:
                summary: Configure an IP allowlist
                description: >-
                  Use one JSON string and separate multiple IP or CIDR entries
                  with `\n`.
                value:
                  name: production
                  expired_time: -1
                  remain_quota: 100000
                  unlimited_quota: false
                  model_limits_enabled: false
                  model_limits: ''
                  allow_ips: |-
                    198.51.100.10
                    203.0.113.0/24
                    2001:db8::/32
                  group: ''
                  cross_group_retry: false
      responses:
        '200':
          description: Create result.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ResultEnvelope'
              examples:
                success:
                  summary: Created
                  value:
                    success: true
                    message: ''
                name_too_long:
                  summary: Name too long
                  value:
                    success: false
                    message: token name is too long
      x-codeSamples:
        - lang: curl
          label: cURL
          source: |-
            curl https://api.cometapi.com/api/token/ \
              -H "Authorization: your-access-token" \
              -H "Content-Type: application/json" \
              -d '{
                "name": "production",
                "expired_time": -1,
                "remain_quota": 100000,
                "unlimited_quota": false,
                "model_limits_enabled": false,
                "model_limits": "",
                "allow_ips": null,
                "group": "",
                "cross_group_retry": false
              }'
        - lang: curl
          label: cURL with IP allowlist
          source: |-
            curl https://api.cometapi.com/api/token/ \
              -H "Authorization: your-access-token" \
              -H "Content-Type: application/json" \
              -d '{
              "name": "production",
              "expired_time": -1,
              "remain_quota": 100000,
              "unlimited_quota": false,
              "model_limits_enabled": false,
              "model_limits": "",
              "allow_ips": "198.51.100.10\n203.0.113.0/24\n2001:db8::/32",
              "group": "",
              "cross_group_retry": false
            }'
components:
  schemas:
    CreateApiKeyRequest:
      type: object
      properties:
        name:
          type: string
          maxLength: 50
          description: >-
            User-readable display name for the API key. The backend accepts up
            to 50 Unicode characters; longer names return `success: false` with
            `token name is too long`.
          example: production
        expired_time:
          type: integer
          description: >-
            Unix timestamp in seconds when the key expires. Use `-1` for no
            expiration. A past timestamp blocks model requests with this key.
          example: -1
        remain_quota:
          type: integer
          description: >-
            Starting quota for the new key in CometAPI internal quota units. If
            this reaches `0` while `unlimited_quota` is `false`, model requests
            with this key are rejected as quota exhausted.
          example: 100000
        unlimited_quota:
          type: boolean
          description: >-
            Whether the key bypasses remaining-quota checks. Set `true` only
            when the key should keep working even if `remain_quota` is `0`.
          example: false
        model_limits_enabled:
          type: boolean
          description: >-
            Whether to restrict this key to specific models. When `true`, only
            model IDs listed in `model_limits` are allowed. When `false`,
            `model_limits` is ignored.
          example: false
        model_limits:
          type: string
          description: >-
            Comma-separated model IDs allowed by this key when
            `model_limits_enabled` is `true`. Use model IDs returned by
            `/v1/models`, for example `<model-id-1>,<model-id-2>`. Use an empty
            string for no model restriction.
          example: ''
        allow_ips:
          type:
            - string
            - 'null'
          description: >-
            Optional IP allowlist. Provide one JSON string with entries
            separated by newline characters (`\n`). Each entry can be a single
            IPv4 address, single IPv6 address, IPv4 CIDR, or IPv6 CIDR. Example
            for three allowlist entries:
            `198.51.100.10\n203.0.113.0/24\n2001:db8::/32`. CometAPI compares
            the model request client IP to this list. Use `null` or `""` to
            disable IP restrictions.
          example: |-
            198.51.100.10
            203.0.113.0/24
            2001:db8::/32
        group:
          type: string
          description: >-
            Optional account group restriction. Use an empty string for no
            explicit group restriction. Non-empty values must be available to
            the account, or the API returns `success: false` with a `no access
            to group` message.
          example: ''
        cross_group_retry:
          type: boolean
          description: >-
            Whether cross-group retry is enabled for automatic group routing.
            This is only meaningful when the key uses an auto-routed group such
            as `auto`.
          example: false
      additionalProperties: false
    ResultEnvelope:
      type: object
      required:
        - success
        - message
      properties:
        success:
          type: boolean
          description: Whether the create operation succeeded.
          example: true
        message:
          type: string
          description: >-
            Backend status message. The value is usually an empty string on
            success.
          example: ''
  securitySchemes:
    accessTokenAuth:
      type: apiKey
      in: header
      name: Authorization
      description: >-
        Personal access token copied from CometAPI Console > Personal Settings.
        Send the raw token value; do not prefix it with `Bearer`.

````