Skip to content

API 概览

Sentinel 提供完整的 RESTful API,用于管理项目、仓库、分析任务和集成。

基础信息

Base URL

http://localhost:8080/api/v1

生产环境请替换为实际域名。

内容类型

所有请求和响应均使用 JSON 格式:

Content-Type: application/json

认证方式

Bearer Token 认证

大多数 API 端点需要认证。在请求头中包含 JWT Token:

http
Authorization: Bearer <your_jwt_token>

Token 获取

通过登录端点获取 Token:

http
POST /api/v1/auth/login
Content-Type: application/json

{
  "identifier": "user@example.com",
  "password": "your_password"
}

响应:

json
{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "expires_at": "2024-01-02T12:00:00Z",
  "user": {
    "user_id": "550e8400-e29b-41d4-a716-446655440000",
    "username": "johndoe",
    "email": "user@example.com",
    "role": "user",
    "status": "active"
  }
}

Token 有效期

  • 有效期: 24 小时
  • 刷新: 目前不支持刷新 Token,过期后需重新登录

错误响应格式

所有错误响应遵循统一格式:

json
{
  "error": "Error message here"
}

HTTP 状态码

状态码说明
200成功
201创建成功
204成功(无内容)
400请求参数错误
401未认证
403无权限
404资源不存在
409冲突(如唯一性约束)
500服务器内部错误

错误示例

400 Bad Request:

json
{
  "error": "Invalid email format"
}

401 Unauthorized:

json
{
  "error": "Invalid or expired token"
}

404 Not Found:

json
{
  "error": "Project not found"
}

409 Conflict:

json
{
  "error": "Username already exists"
}

分页

分页参数

列表查询支持分页参数:

参数类型默认值说明
limitinteger20每页数量 (1-100)
offsetinteger0偏移量

示例:

http
GET /api/v1/projects?limit=10&offset=20

分页响应

json
{
  "projects": [ /* ... */ ],
  "total": 45
}

字段说明:

  • total: 总记录数
  • {resource}: 当前页数据数组

过滤和排序

状态过滤

部分端点支持状态过滤:

http
GET /api/v1/analysis?status=running

支持的状态值:

  • submitted
  • pending
  • running
  • completed
  • failed
  • cancelled

排序

默认按创建时间倒序排序(最新的在前)。

常用响应字段

时间戳字段

所有时间戳使用 ISO 8601 格式(UTC):

json
{
  "created_at": "2024-01-01T12:00:00Z",
  "updated_at": "2024-01-01T13:00:00Z"
}

UUID 字段

所有资源 ID 使用 UUID v4 格式:

json
{
  "project_id": "550e8400-e29b-41d4-a716-446655440000"
}

可选字段

可选字段在为空时可能返回 null 或不存在:

json
{
  "description": null,  // 或者字段不存在
  "completed_at": null
}

API 端点分组

认证相关

资源管理

集成相关

实时通信

速率限制

目前未实施速率限制,但建议客户端:

  • 合理控制请求频率
  • 使用缓存减少重复请求
  • 避免大量并发请求

CORS 配置

生产环境 CORS 配置:

  • 允许的源: http://localhost:3000(开发环境)
  • 允许的方法: GET, POST, PUT, PATCH, DELETE, OPTIONS
  • 允许的头: Authorization, Content-Type, Accept
  • 允许凭证: true

最佳实践

1. 错误处理

始终检查 HTTP 状态码和错误响应:

typescript
try {
  const response = await api.get('/api/v1/projects');
  return response.data;
} catch (error) {
  if (error.response) {
    // 服务器返回错误
    console.error(error.response.data.error);
  } else {
    // 网络错误
    console.error('Network error');
  }
}

2. Token 管理

  • 将 Token 存储在 localStorage 或 sessionStorage
  • 在请求拦截器中自动添加 Authorization 头
  • 401 响应时自动跳转到登录页
typescript
// Axios 拦截器示例
axios.interceptors.request.use(config => {
  const token = localStorage.getItem('token');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

axios.interceptors.response.use(
  response => response,
  error => {
    if (error.response?.status === 401) {
      // 清除 Token 并跳转到登录页
      localStorage.removeItem('token');
      window.location.href = '/login';
    }
    return Promise.reject(error);
  }
);

3. 数据验证

客户端在发送请求前进行基本验证:

typescript
// 邮箱验证
const isValidEmail = (email: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);

// 密码验证(至少8位)
const isValidPassword = (password: string) => password.length >= 8;

// 用户名验证(3-30位,字母数字下划线)
const isValidUsername = (username: string) => /^[a-zA-Z0-9_]{3,30}$/.test(username);

4. 分页处理

使用游标或偏移分页:

typescript
const fetchAllProjects = async () => {
  const allProjects = [];
  let offset = 0;
  const limit = 50;
  
  while (true) {
    const response = await api.get(`/api/v1/projects?limit=${limit}&offset=${offset}`);
    allProjects.push(...response.data.projects);
    
    if (response.data.projects.length < limit) {
      break; // 最后一页
    }
    offset += limit;
  }
  
  return allProjects;
};

5. 实时更新

使用 SSE 获取实时状态:

typescript
const connectSSE = (analysisId: string) => {
  const token = localStorage.getItem('token');
  const url = `/api/v1/sse/analysis/${analysisId}?token=${token}`;
  
  const eventSource = new EventSource(url);
  
  eventSource.onmessage = (event) => {
    const data = JSON.parse(event.data);
    console.log('Status update:', data);
  };
  
  eventSource.onerror = () => {
    eventSource.close();
  };
  
  return eventSource;
};

API 版本

当前 API 版本: v1

  • 所有端点前缀: /api/v1
  • 版本变更会提前通知
  • 旧版本将维护至少 6 个月

工具和 SDK

官方 SDK

目前没有官方 SDK,欢迎社区贡献。

推荐的 HTTP 客户端

  • JavaScript/TypeScript: axios, fetch
  • Rust: reqwest
  • Python: httpx, requests
  • Go: net/http, resty

Postman Collection

敬请期待。

支持和反馈

下一步

选择你需要的 API 分类:

Released under the MIT License.