OpenRouter 入门与概览

OpenRouter 入门与概览

管理 API 密钥

3 分钟阅读

管理 API 密钥

以编程方式管理 API 密钥

OpenRouter 提供用于以编程方式管理 API 密钥的端点,便于需要自动分发或轮换密钥的应用创建和管理密钥。

创建管理 API 密钥

要使用密钥管理 API,你首先需要创建一把管理 API 密钥:

  1. 前往 管理 API 密钥页面
  2. 点击「创建新密钥(Create New Key)」
  3. 完成密钥创建流程

管理密钥不能用于调用 OpenRouter 的补全端点——它们专用于管理操作。

使用场景

以编程方式管理密钥的常见场景包括:

  • SaaS 应用:为每个客户实例自动创建唯一的 API 密钥
  • 密钥轮换:定期轮换 API 密钥以满足安全合规要求
  • 用量监控:跟踪密钥用量,并自动禁用超出限额的密钥(可选择按日 / 周 / 月重置限额)

使用示例

所有密钥管理端点都位于 /api/v1/keys 下,并需要在 Authorization 请求头中提供管理 API 密钥。

import { OpenRouter } from '@openrouter/sdk';

const openRouter = new OpenRouter({
  apiKey: 'your-management-key', // 使用你的管理 API 密钥
});

// 列出最近的 100 把 API 密钥
const keys = await openRouter.apiKeys.list();

// 可以使用 offset 参数分页
const keysPage2 = await openRouter.apiKeys.list({ offset: 100 });

// 创建一把新的 API 密钥
const newKey = await openRouter.apiKeys.create({
  name: '客户实例密钥',
  limit: 1000, // 可选的额度上限
});

// 获取特定密钥
const keyHash = '<YOUR_KEY_HASH>';
const key = await openRouter.apiKeys.get(keyHash);

// 更新密钥
const updatedKey = await openRouter.apiKeys.update(keyHash, {
  name: '更新后的密钥名称',
  disabled: true, // 可选:禁用该密钥
  includeByokInLimit: false, // 可选:控制限额中是否计入 BYOK 用量
  limitReset: 'daily', // 可选:每天 UTC 午夜重置限额
});

// 删除密钥
await openRouter.apiKeys.delete(keyHash);

响应格式

API 响应返回包含密钥信息的 JSON 对象:

{
  "data": [
    {
      "created_at": "2025-02-19T20:52:27.363244+00:00",
      "updated_at": "2025-02-19T21:24:11.708154+00:00",
      "hash": "<YOUR_KEY_HASH>",
      "label": "sk-or-v1-abc...123",
      "name": "Customer Key",
      "disabled": false,
      "limit": 10,
      "limit_remaining": 10,
      "limit_reset": null,
      "include_byok_in_limit": false,
      "usage": 0,
      "usage_daily": 0,
      "usage_weekly": 0,
      "usage_monthly": 0,
      "byok_usage": 0,
      "byok_usage_daily": 0,
      "byok_usage_weekly": 0,
      "byok_usage_monthly": 0
    }
  ]
}

创建新密钥时,响应会包含密钥字符串本身。更多信息见 API 参考