认证
所有 API 请求都必须经过认证。TopMat API 通过 Authorization 头使用 API Key 认证:
- API Key:用于任务接口(
/api/v2/task/*)和数据库发现接口(/api/v2/database/*),格式为Authorization: Bearer tk_...。
API Key 权限范围
Section titled “API Key 权限范围”同一个 API Key 可访问任务接口与数据库读取/发现接口。与数据库访问权限相关的行为:
POST /api/v2/database/{db_id}/phases会校验当前用户对该数据库的订阅访问权限,无有效订阅时返回403。- 创建任务接口
POST /api/v2/task同样会校验task_config.tdb_code对应数据库的订阅访问权限,无有效订阅时返回403(详见数据库接口)。
验证 API Key
Section titled “验证 API Key”调用 GET /api/v2/key/info 可以验证当前 Key 并查看其归属信息:
curl https://api.topmaterial-tech.com/api/v2/key/info \ -H "Authorization: Bearer tk_0123456789abcdef0123456789abcdef"{ "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" }}| 字段 | 类型 | 说明 |
|---|---|---|
id | integer | API Key 的数据库 ID。 |
api_key | string | API Key 本身。 |
key_name | string | Key 的名称。 |
is_active | boolean | 是否处于激活状态。 |
created_at | string | 创建时间。 |
last_used_at | string | null | 最近使用时间;未提供时表示从未使用。 |
expires_at | string | null | 过期时间;未提供时表示不过期。 |
user | object | Key 所属用户信息。 |
user.id | string (UUID) | 用户 ID,可用于 GET /api/v2/database/user/status 的 user_id 参数。 |
user.username | string | 用户名。 |
user.email | string | null | 用户邮箱。 |
user.subscription_level | string | 用户当前订阅等级。 |
user.subscription_expires_at | string | null | 订阅过期时间;未提供时表示无固定过期时间。 |
为 null 的字段(如 expires_at、user.subscription_expires_at)可能直接不出现在响应 JSON 中,而不是以 null 值返回;客户端应将这些字段按可选处理。
API Key 格式
Section titled “API Key 格式”API Key 以 tk_ 前缀开头,后跟 32 位字母数字字符:
tk_0123456789abcdef0123456789abcdef每次请求都使用 Bearer token 方案携带 API Key:
curl https://api.topmaterial-tech.com/api/v2/task/list \ -H "Authorization: Bearer tk_0123456789abcdef0123456789abcdef"API Key 认证中间件按以下顺序依次检查,任一失败即返回对应错误:
- 必须存在
Authorization头。 - 头信息必须以
Bearer开头。 - API Key 必须以
tk_开头。 - API Key 长度至少为 10 个字符(实际签发的 Key 为 35 个字符)。
- Key 必须存在于数据库中。
- Key 必须处于激活状态(
is_active: true)。 - Key 不能过期(
expires_at为未来时间或未设置)。
认证通过后,该 Key 的 last_used_at 会在每次请求时自动更新。
| 状态码 | 含义 | 示例消息 |
|---|---|---|
401 | 请求头缺失 | Missing Authorization header |
401 | Bearer 格式错误 | Invalid Authorization header format, expected 'Bearer <token>' |
401 | Key 前缀错误 | API key must start with 'tk_' prefix |
401 | Key 长度过短 | API key is too short |
401 | Key 不存在 | invalid API key |
403 | Key 已禁用 | API key is disabled |
403 | Key 已过期 | API key has expired |
无效 Key(invalid API key)的 401 响应可能额外包含 details 字段(如 API key not found in database)说明具体原因;客户端应以 error 字段为准。
管理 API Key
Section titled “管理 API Key”API Key 可通过 Web 控制台 管理。每个 Key 归属于创建者本人,可随时命名、禁用或删除。