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

# APIキー管理

> System APIを通じてAPIキーを作成、検索、表示、更新、無効化、ローテーション、削除します。

## 概要

APIキーは`/api/token`で管理します。これらのエンドポイントでは、[認証とクォータ](/ja/api-reference/system-api/authentication-and-quota)で説明するシステムアクセストークンを使用します。

<Warning>
  `PUT /api/token/`は、JSON Merge Patchではなく、変更可能な設定の全体更新を行います。保持する必要があるすべての設定を含めてください。
</Warning>

## 変更可能なフィールド

| フィールド | 型 | 説明 |
| - | - | - |
| `id` | integer | 更新時に必須 |
| `name` | string | 表示名。最大50文字 |
| `expired_time` | integer | 秒単位のUnixタイムスタンプ。`-1`は無期限を意味します。 |
| `remain_quota` | integer | 内部単位での残りクォータ |
| `unlimited_quota` | boolean | `true`の場合、キー単位のクォータ上限を無効にします。 |
| `model_limits_enabled` | boolean | モデルの許可リストを有効にします |
| `model_limits` | string | カンマ区切りのモデルID |
| `allow_ips` | string or null | 改行で区切ったIPアドレスまたはCIDR範囲。空文字列または`null`は制限なしを意味します |
| `group` | string | ルーティングと課金のグループ |
| `cross_group_retry` | boolean | グループをまたぐ再試行。対応する自動グループでのみ意味があります |
| `smart_routing` | boolean | レコードをスマートルーティングキーとして指定します |
| `smart_route_tiers` | string | JSONエンコードされたスマートルーティングのティア設定 |

## 標準APIキーを作成

```bash theme={null}
curl -fsS -X POST "$BASE_URL/api/token/" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "New-Api-User: $USER_ID" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "ci-deployment",
    "expired_time": -1,
    "remain_quota": 0,
    "unlimited_quota": true,
    "model_limits_enabled": false,
    "model_limits": "",
    "allow_ips": "",
    "group": "default",
    "cross_group_retry": false,
    "smart_routing": false,
    "smart_route_tiers": ""
  }' | jq
```

作成成功時のレスポンスにはレコードIDが含まれません。一意の名前を使用し、一覧取得または検索で新しいレコードを見つけてください。

## 一覧表示と検索

標準キーの一覧では、デフォルトでスマートルーティングのキーが除外されます。

```bash theme={null}
curl -fsS "$BASE_URL/api/token/?p=1&size=20" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "New-Api-User: $USER_ID" | jq
```

すべてのキーを含めるには、`exclude_smart_routing=false`を設定してください。

```bash theme={null}
curl -fsS "$BASE_URL/api/token/?p=1&size=20&exclude_smart_routing=false" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "New-Api-User: $USER_ID" | jq
```

ページサイズのパラメータ名は`size`、`page_size`、`ps`に対応しています。最大ページサイズは100です。

名前または保存されたキーの値で検索します。

```bash theme={null}
curl -fsS --get "$BASE_URL/api/token/search" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "New-Api-User: $USER_ID" \
  --data-urlencode "keyword=ci-deployment" \
  --data-urlencode "p=1" \
  --data-urlencode "size=20" | jq
```

任意の`token`クエリパラメーターは、`sk-`プレフィックスの有無にかかわらずキーを受け付けます。一覧、検索、取得のレスポンスでは、キーの値は常にマスクされます。

## 取得とマスク解除

マスク済みのレコードを取得します。

```bash theme={null}
curl -fsS "$BASE_URL/api/token/42" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "New-Api-User: $USER_ID" | jq
```

保存された値を完全な形で取得します。

```bash theme={null}
stored_key=$(curl -fsS -X POST "$BASE_URL/api/token/42/key" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "New-Api-User: $USER_ID" \
  | jq -er '.data.key')

api_key="sk-${stored_key#sk-}"
```

キーの表示用エンドポイントは、`sk-`を追加せずに保存された値を返します。レスポンスはシークレットとして扱い、画面やログに出力せず、シークレットマネージャーに直接書き込んでください。

1回のリクエストで最大100個のキーを表示します。

```bash theme={null}
curl -fsS -X POST "$BASE_URL/api/token/batch/keys" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "New-Api-User: $USER_ID" \
  -H "Content-Type: application/json" \
  -d '{"ids":[42,43]}'
```

## キーを安全に更新

現在のレコードを読み取り、変更可能な全フィールドを含むペイロードを構築し、意図した値だけを変更してください。

```bash theme={null}
current=$(curl -fsS "$BASE_URL/api/token/42" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "New-Api-User: $USER_ID")

payload=$(jq '.data | {
  id,
  name,
  expired_time,
  remain_quota,
  unlimited_quota,
  model_limits_enabled,
  model_limits,
  allow_ips,
  group,
  cross_group_retry,
  smart_routing,
  smart_route_tiers
} | .name = "ci-deployment-v2"' <<< "$current")

curl -fsS -X PUT "$BASE_URL/api/token/" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "New-Api-User: $USER_ID" \
  -H "Content-Type: application/json" \
  -d "$payload" | jq
```

この読み取り・変更・書き込みのパターンにより、モデル制限とスマートルーティング設定が維持されます。

## 有効化または無効化

ステータスのみを更新する場合、ほかのすべての設定は保持されます。

```bash theme={null}
curl -fsS -X PUT "$BASE_URL/api/token/?status_only=true" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "New-Api-User: $USER_ID" \
  -H "Content-Type: application/json" \
  -d '{"id":42,"status":2}' | jq
```

| ステータス | 意味 |
| - | - |
| `1` | 有効 |
| `2` | 手動で無効化済み |
| `3` | 有効期限切れ |
| `4` | クォータを使い切りました |

有効期限切れ、またはクォータを使い切ったキーは、有効期限またはクォータの条件を修正するまで有効にできません。

## キーの削除

キーを1つ削除します。

```bash theme={null}
curl -fsS -X DELETE "$BASE_URL/api/token/42" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "New-Api-User: $USER_ID" | jq
```

所有する複数のキーを削除します。

```bash theme={null}
curl -fsS -X POST "$BASE_URL/api/token/batch" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "New-Api-User: $USER_ID" \
  -H "Content-Type: application/json" \
  -d '{"ids":[42,43]}' | jq
```

一括処理レスポンスの`data`の値は、実際に削除されたレコード数です。

## ライフサイクル全体のスクリプト

このスクリプトは、米ドル建ての上限を設定した有効期間1時間のキーを作成し、そのキーを検索して、シークレットをログに記録せずに取得し、更新、無効化、削除を行います。

```bash theme={null}
#!/usr/bin/env bash
set -euo pipefail

: "${BASE_URL:=https://api.mixroute.ai}"
: "${ACCESS_TOKEN:?Set ACCESS_TOKEN}"
: "${USER_ID:?Set USER_ID}"

auth=(
  -H "Authorization: Bearer $ACCESS_TOKEN"
  -H "New-Api-User: $USER_ID"
)

name="automation-$(date +%s)-$RANDOM"
token_id=""

delete_token() {
  local response
  response=$(curl -fsS -X DELETE "$BASE_URL/api/token/$token_id" \
    "${auth[@]}")
  jq -e '.success == true' <<< "$response" >/dev/null
}

cleanup() {
  if [[ -n "$token_id" ]]; then
    delete_token >/dev/null 2>&1 || true
  fi
}
trap cleanup EXIT

quota_per_unit=$(curl -fsS "$BASE_URL/api/status" | jq -er '.data.quota_per_unit')
expires_at=$(( $(date +%s) + 3600 ))
quota=$(( 5 * quota_per_unit ))

create_payload=$(jq -n \
  --arg name "$name" \
  --argjson expires "$expires_at" \
  --argjson quota "$quota" '{
    name: $name,
    expired_time: $expires,
    remain_quota: $quota,
    unlimited_quota: false,
    model_limits_enabled: false,
    model_limits: "",
    allow_ips: "",
    group: "default",
    cross_group_retry: false,
    smart_routing: false,
    smart_route_tiers: ""
  }')

created=$(curl -fsS -X POST "$BASE_URL/api/token/" \
  "${auth[@]}" -H "Content-Type: application/json" \
  -d "$create_payload")
jq -e '.success == true' <<< "$created" >/dev/null

found=$(curl -fsS --get "$BASE_URL/api/token/search" \
  "${auth[@]}" --data-urlencode "keyword=$name" \
  --data-urlencode "p=1" --data-urlencode "size=10")
token_id=$(jq -er --arg name "$name" '
  [.data.items[] | select(.name == $name)]
  | if length == 1 then .[0].id
    else error("expected exactly one matching API key")
    end
' <<< "$found")

stored_key=$(curl -fsS -X POST "$BASE_URL/api/token/$token_id/key" \
  "${auth[@]}" | jq -er '.data.key')
api_key="sk-${stored_key#sk-}"
# Replace this no-op with your secrets-manager command.
: "$api_key"
unset stored_key api_key

current=$(curl -fsS "$BASE_URL/api/token/$token_id" "${auth[@]}")
update_payload=$(jq --argjson quota "$((10 * quota_per_unit))" '.data | {
  id, name, expired_time, remain_quota, unlimited_quota,
  model_limits_enabled, model_limits, allow_ips, group,
  cross_group_retry, smart_routing, smart_route_tiers
} | .remain_quota = $quota' <<< "$current")

curl -fsS -X PUT "$BASE_URL/api/token/" \
  "${auth[@]}" -H "Content-Type: application/json" \
  -d "$update_payload" | jq -e '.success == true' >/dev/null

curl -fsS -X PUT "$BASE_URL/api/token/?status_only=true" \
  "${auth[@]}" -H "Content-Type: application/json" \
  -d "{\"id\":$token_id,\"status\":2}" \
  | jq -e '.success == true' >/dev/null

delete_token
token_id=""
trap - EXIT
echo "API key lifecycle completed"
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.