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

# 身份验证

> 使用 API key 保护你的 TokenLab API 请求

## API key

所有 TokenLab API 请求都需要 API key。

对于兼容 OpenAI 的端点，请按如下方式发送：

```bash theme={null}
Authorization: Bearer sk-your-api-key
```

对于兼容 Anthropic 的 `/v1/messages` 请求，你也可以使用：

```bash theme={null}
x-api-key: sk-your-api-key
```

## 获取你的 API key

1. 登录你的 [TokenLab Dashboard](https://tokenlab.sh/dashboard)
2. 打开 **API Keys**
3. 创建一个新 key
4. 为其指定一个便于识别的名称
5. 立即复制它，因为它只会显示一次

<Warning>
  * 绝不要在客户端代码中暴露 API key
  * 绝不要将 API key 提交到版本控制
  * 使用环境变量或 secret manager
  * 定期轮换 key
  * 删除未使用的 key
</Warning>

## 使用 API key

<CodeGroup>
  ```bash cURL theme={null}
  curl https://api.tokenlab.sh/v1/responses \
    -H "Authorization: Bearer $TOKENLAB_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "model": "gpt-5.4",
      "input": "Hello!"
    }'
  ```

  ```python Python theme={null}
  import os
  from openai import OpenAI

  client = OpenAI(
      api_key=os.environ.get("TOKENLAB_API_KEY"),
      base_url="https://api.tokenlab.sh/v1"
  )
  ```

  ```javascript JavaScript theme={null}
  import OpenAI from 'openai';

  const client = new OpenAI({
    apiKey: process.env.TOKENLAB_API_KEY,
    baseURL: 'https://api.tokenlab.sh/v1'
  });
  ```
</CodeGroup>

## API key 特性

### 使用限制

你可以为每个 API key 设置使用限制：

| 设置              | 描述                |
| --------------- | ----------------- |
| **No Limit**    | key 可无限制地使用你的账户余额 |
| **Fixed Limit** | key 在达到指定金额后将停止工作 |

### key 前缀

所有 TokenLab API key 都以 `sk-` 开头。

## Anthropic 兼容性

对于 `/v1/messages` 端点，Anthropic 风格的请求头可按预期工作：

```bash theme={null}
curl https://api.tokenlab.sh/v1/messages \
  -H "x-api-key: sk-your-api-key" \
  -H "anthropic-version: 2023-06-01" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "claude-sonnet-4-6",
    "max_tokens": 1024,
    "messages": [{"role": "user", "content": "Hello!"}]
  }'
```

<Note>
  对于兼容 OpenAI 的端点，例如 `/v1/responses`、`/v1/chat/completions`、`/v1/models` 以及大多数其他 TokenLab 路由，请使用 `Authorization: Bearer ...`。
</Note>

## 错误响应

| 状态码 | 类型                     | 代码                     | 描述               |
| --- | ---------------------- | ---------------------- | ---------------- |
| 401 | `invalid_api_key`      | `invalid_api_key`      | 缺少或无效的 API key   |
| 401 | `expired_api_key`      | `expired_api_key`      | API key 已被撤销     |
| 402 | `insufficient_balance` | `insufficient_balance` | 账户余额不足           |
| 402 | `quota_exceeded`       | `quota_exceeded`       | 已达到 API key 使用限制 |

示例：

```json theme={null}
{
  "error": {
    "message": "Invalid API key provided",
    "type": "invalid_api_key",
    "code": "invalid_api_key"
  }
}
```
