Files
ai4se-harness-suite/example-project/docs/standards/api-design.md
ning-inspire 26975e5c3a Initial commit: ai4se-harness-suite
Import harness suite (skills, installers, overnight-runner, docs) as a fresh history for InspireChina.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-17 09:57:41 +08:00

2.3 KiB
Raw Blame History

API 规范

基础

  • RESTful 风格
  • URL 一律小写连字符(kebab-case)
  • 名词使用复数(如 /users、/appointments)
  • API 前缀 /api/v1/

请求

  • GET/DELETE 参数通过 Query String
  • POST/PUT 参数通过 JSON Body
  • Content-Type: application/json
  • 认证通过 Authorization: Bearer <token> 请求头

响应

  • 成功:直接返回数据体
  • 错误:统一格式 {errorCode, errorMessage, data}

HTTP 状态码

状态码 含义 使用场景
200 成功 正常返回
400 参数错误 参数校验失败 / 业务参数错误
401 未授权 Token 缺失 / 无效 / 过期
403 无权限 非管理员访问 /admin
404 不存在 资源 ID 不存在
409 业务冲突 重复预约 / 状态冲突
500 服务器错误 未捕获异常

分页

  • 入参:page(从 1 开始)、pageSize(默认 20)
  • 出参:{records, total, page, pageSize}

前端 API 调用规范

Service 层封装

每个领域对应一个 service 文件,统一通过 Axios 实例调用:

// src/services/appointmentService.ts
import api from '@/utils/axios'

export const appointmentService = {
  list: () => api.get('/appointments'),
  getById: (id: string) => api.get(`/appointments/${id}`),
  create: (data: CreateAppointmentDto) => api.post('/appointments', data),
  cancel: (id: string, reason?: string) => api.put(`/appointments/${id}/cancel`, { reason }),
}

Axios 实例配置

// src/utils/axios.ts
import axios from 'axios'

const api = axios.create({ baseURL: '/api/v1' })

// 请求拦截器:自动附加 JWT
api.interceptors.request.use(config => {
  const token = localStorage.getItem('token')
  if (token) config.headers.Authorization = `Bearer ${token}`
  return config
})

// 响应拦截器:统一错误处理与 401 跳转
api.interceptors.response.use(
  res => res,
  error => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

export default api

响应处理

  • 成功响应直接返回 data
  • 业务错误(400/409)在调用处 catch 处理,展示错误消息
  • 网络/系统错误(500)由拦截器统一提示