跳转到内容

认证

所有 API 请求都必须经过认证。TopMat API 通过 Authorization 头使用 API Key 认证:

  • API Key:用于任务接口(/api/v2/task/*)和数据库发现接口(/api/v2/database/*),格式为 Authorization: Bearer tk_...

同一个 API Key 可访问任务接口与数据库读取/发现接口。与数据库访问权限相关的行为:

  • POST /api/v2/database/{db_id}/phases 会校验当前用户对该数据库的订阅访问权限,无有效订阅时返回 403
  • 创建任务接口 POST /api/v2/task 同样会校验 task_config.tdb_code 对应数据库的订阅访问权限,无有效订阅时返回 403(详见数据库接口)。

调用 GET /api/v2/key/info 可以验证当前 Key 并查看其归属信息:

查询 API Key 信息
curl https://api.topmaterial-tech.com/api/v2/key/info \
-H "Authorization: Bearer tk_0123456789abcdef0123456789abcdef"
响应示例:API Key 信息
{
"id": 1,
"api_key": "tk_0123456789abcdef0123456789abcdef",
"key_name": "Production API Key",
"is_active": true,
"created_at": "2026-01-01T00:00:00Z",
"last_used_at": "2026-05-20T08:00:00Z",
"expires_at": "2026-12-31T23:59:59Z",
"user": {
"id": "550e8400-e29b-41d4-a716-446655440000",
"username": "johndoe",
"email": "john.doe@example.com",
"subscription_level": "pro",
"subscription_expires_at": "2026-12-31T23:59:59Z"
}
}
字段类型说明
idintegerAPI Key 的数据库 ID。
api_keystringAPI Key 本身。
key_namestringKey 的名称。
is_activeboolean是否处于激活状态。
created_atstring创建时间。
last_used_atstring | null最近使用时间;未提供时表示从未使用。
expires_atstring | null过期时间;未提供时表示不过期。
userobjectKey 所属用户信息。
user.idstring (UUID)用户 ID,可用于 GET /api/v2/database/user/statususer_id 参数。
user.usernamestring用户名。
user.emailstring | null用户邮箱。
user.subscription_levelstring用户当前订阅等级。
user.subscription_expires_atstring | null订阅过期时间;未提供时表示无固定过期时间。

null 的字段(如 expires_atuser.subscription_expires_at)可能直接不出现在响应 JSON 中,而不是以 null 值返回;客户端应将这些字段按可选处理。

API Key 以 tk_ 前缀开头,后跟 32 位字母数字字符:

API Key 格式示例
tk_0123456789abcdef0123456789abcdef

每次请求都使用 Bearer token 方案携带 API Key:

携带 API Key 发送请求
curl https://api.topmaterial-tech.com/api/v2/task/list \
-H "Authorization: Bearer tk_0123456789abcdef0123456789abcdef"

API Key 认证中间件按以下顺序依次检查,任一失败即返回对应错误:

  1. 必须存在 Authorization 头。
  2. 头信息必须以 Bearer 开头。
  3. API Key 必须以 tk_ 开头。
  4. API Key 长度至少为 10 个字符(实际签发的 Key 为 35 个字符)。
  5. Key 必须存在于数据库中。
  6. Key 必须处于激活状态(is_active: true)。
  7. Key 不能过期(expires_at 为未来时间或未设置)。

认证通过后,该 Key 的 last_used_at 会在每次请求时自动更新。

状态码含义示例消息
401请求头缺失Missing Authorization header
401Bearer 格式错误Invalid Authorization header format, expected 'Bearer <token>'
401Key 前缀错误API key must start with 'tk_' prefix
401Key 长度过短API key is too short
401Key 不存在invalid API key
403Key 已禁用API key is disabled
403Key 已过期API key has expired

无效 Key(invalid API key)的 401 响应可能额外包含 details 字段(如 API key not found in database)说明具体原因;客户端应以 error 字段为准。

API Key 可通过 Web 控制台 管理。每个 Key 归属于创建者本人,可随时命名、禁用或删除。