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

# API Key 是什么？如何获取和保管

> 介绍 API Key 的含义、作用和安全保管要则，帮助初次使用 Sub2API 的用户快速上手。

API Key 是访问 Sub2API 的身份凭证，相当于你的 API 密码。每次调用接口时，都需要在 HTTP Header 中带上它，网关才能识别你的身份并计费。

## API Key 是什么

API Key 是一串由系统生成的随机字符串，用于在程序化调用中对请求方进行身份验证。它与登录密码不同，后者用于浏览器端的控制台登录，而 API Key 用于代码和脚本中的自动鉴权。

Sub2API 采用 Bearer Token 方案：你只需在每个请求的 `Authorization` Header 中放入 `Bearer YOUR_API_KEY`，即可通过认证。

## 如何获取 API Key

获取 API Key 需要前往 Sub2API 控制台。大致流程如下：

<Steps>
  <Step title="登录控制台">
    打开 [https://sub2api.ruilinlu.com/login](https://sub2api.ruilinlu.com/login) 并登录你的账户。

    <Note>
      目前注册功能已关闭，如需开通账户请联系管理员。
    </Note>
  </Step>

  <Step title="进入 API Key 页面">
    登录后，在控制台中找到 API Key 管理页面。通常位于左侧菜单或顶部导航栏中。
  </Step>

  <Step title="创建新 Key">
    点击“创建”按钮，系统会生成一个新的 API Key。请务必在弹出窗口中立即复制保存，因为 Key 通常只会完整显示一次。
  </Step>
</Steps>

更详细的图文步骤可参考 [创建 API Key](/getting-started/create-api-key)。

## 如何在请求中使用

所有请求都必须在 Header 中携带 API Key，格式如下：

```http theme={null}
Authorization: Bearer YOUR_API_KEY
```

<Warning>
  注意 `Bearer` 与 Key 之间必须有一个空格。缺少空格、写错大小写、或在 Key 前后混入多余空格都会导致 401 错误。
</Warning>

<CodeGroup>
  ```python Python theme={null}
  import requests

  headers = {
      "Authorization": "Bearer YOUR_API_KEY",
      "Content-Type": "application/json"
  }

  response = requests.post(
      "https://sub2api.ruilinlu.com/v1/chat/completions",
      headers=headers,
      json={"model": "gpt-4o", "messages": [{"role": "user", "content": "Hello"}]}
  )
  ```

  ```bash cURL theme={null}
  curl https://sub2api.ruilinlu.com/v1/chat/completions \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{"model": "gpt-4o", "messages": [{"role": "user", "content": "Hello"}]}'
  ```
</CodeGroup>

## 安全保管建议

<CardGroup cols={2}>
  <Card title="不要分享" icon="lock">
    你的 API Key 等同于账户权限，泄露后他人可使用你的额度并产生费用。
  </Card>

  <Card title="不要提交到代码仓库" icon="code-branch">
    避免将 Key 硬编码在代码中并推送到 GitHub 等公开仓库。应使用环境变量或密钥管理服务。
  </Card>

  <Card title="使用环境变量" icon="terminal">
    在代码中通过环境变量读取 Key。例如 Python 中使用 `os.environ.get("SUB2API_KEY")`。
  </Card>

  <Card title="发现泄露立即撤销" icon="triangle-exclamation">
    如果怀疑 Key 已泄露，请立即在控制台中删除该 Key 并创建新的 Key。
  </Card>
</CardGroup>

<Tip>
  建议为不同环境（开发、测试、生产）创建独立的 API Key，方便权限隔离和用量追踪。
</Tip>
