7b2f3d77ca
- 新增 backend/design/支付模块架构概览.md - 新增 backend/design/支付模块数据库设计.md (21张表 DDL) - 新增 backend/design/支付模块接口设计.md - git.dev.vifo.cc → git.vifo.cc 全局替换
16 KiB
16 KiB
API 设计规范
睿核科技通用平台框架 RESTful API 统一设计标准
一、接口分类
| 分类 | 路径前缀 | 认证 | 说明 |
|---|---|---|---|
| 对外接口 | /{模块}/api/** |
OAuth2 Token | 对外提供的业务接口 |
| 内部接口 | /{模块}/inner/** |
@Inner + INTERNAL_REQUEST |
微服务间 Feign 调用 |
| 入口接口 | /{模块}/entry/** |
无需认证 | 对外入口(登录、注册) |
| 回调接口 | /{模块}/notify/** |
无需认证 | 第三方回调(支付、Webhook) |
| 管理接口 | /{模块}/admin/** |
需管理员权限 | 后台管理 |
二、URL 设计规范
2.1 对外接口(RESTful)
GET /{version}/{模块}/{资源} # 列表查询
GET /{version}/{模块}/{资源}/{id} # 详情查询
POST /{version}/{模块}/{资源} # 新增
PUT /{version}/{模块}/{资源}/{id} # 全量更新
PATCH /{version}/{模块}/{资源}/{id} # 局部更新
DELETE /{version}/{模块}/{资源}/{id} # 删除
示例:
GET /v1/user/users?page=1&size=10 # 查询用户列表
GET /v1/user/users/1001 # 查询用户详情
POST /v1/user/users # 新增用户
PUT /v1/user/users/1001 # 全量更新用户
PATCH /v1/user/users/1001 # 局部更新(如只改状态)
DELETE /v1/user/users/1001 # 删除用户
2.2 内部接口(Feign)
GET /{模块}/inner/{功能}/{方法}
示例:
GET /user/inner/auth/loadByUsername/{username}
GET /system/inner/client/getById/{clientId}
2.3 版本控制
- URI 版本(推荐):
/v1/user/users - Header 版本(可选):
Accept: application/vnd.rui.v1+json
三、请求规范
3.1 HTTP 方法
| 方法 | 用途 | 幂等性 |
|---|---|---|
| GET | 查询 | ✅ |
| POST | 新增/提交 | ❌ |
| PUT | 全量更新 | ✅ |
| PATCH | 局部更新 | ❌ |
| DELETE | 删除 | ✅ |
3.2 Content-Type
Content-Type: application/json; charset=utf-8
3.3 请求头规范
| Header | 必填 | 说明 |
|---|---|---|
| Authorization | 是(除 entry/notify) | Bearer {access_token} |
| Content-Type | 是 | application/json |
| X-Request-Id | 否 | 请求追踪 ID(网关自动生成) |
| X-Tenant-Id | 否 | 租户 ID(后端自动注入) |
| Accept-Language | 否 | 语言偏好 zh-CN / en-US |
3.4 分页参数
GET /v1/user/users?page=1&size=10&sort=createdAt,desc
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| page | int | 1 | 当前页码(从1开始) |
| size | int | 10 | 每页条数(最大100) |
| sort | string | createdAt,desc | 排序字段和方向 |
3.5 查询参数
GET /v1/user/users?username=admin&status=1&createdAt_start=2024-01-01&createdAt_end=2024-12-31
规则:
- 精确匹配:字段名直接等于值
status=1 - 模糊匹配:字段名加后缀
_likeusername_like=admin - 范围查询:字段名加后缀
_start/_endcreatedAt_start=2024-01-01 - 多值查询:字段名加后缀
_instatus_in=1,2
四、响应规范
4.1 统一响应格式
详细规范见 Result 统一响应类
{
"error": 0,
"message": "操作成功",
"data": {}
}
4.2 分页响应格式
{
"error": 0,
"message": "操作成功",
"data": {
"records": [],
"total": 100,
"size": 10,
"current": 1,
"pages": 10
}
}
4.3 HTTP 状态码
| 状态码 | 含义 | 使用场景 |
|---|---|---|
| 200 | OK | 查询成功、更新成功 |
| 201 | Created | 新增成功 |
| 204 | No Content | 删除成功(无返回体) |
| 400 | Bad Request | 参数校验失败 |
| 401 | Unauthorized | 未登录/Token 过期 |
| 403 | Forbidden | 无权限访问 |
| 404 | Not Found | 资源不存在 |
| 409 | Conflict | 资源冲突(如重复提交) |
| 429 | Too Many Requests | 请求过于频繁 |
| 500 | Internal Server Error | 服务器内部错误 |
4.4 错误码规范
| 区间 | 模块 | 示例 |
|---|---|---|
| 0 | 通用成功 | 0: 操作成功 |
| 1 | 通用失败 | 1: 操作失败 |
| 400-499 | HTTP 标准 | 401: 未授权, 404: 资源不存在 |
| 4000-4099 | 认证模块 | 4001: Token 已过期, 4002: Token 无效 |
| 4100-4199 | 用户信息 | 4101: 用户不存在, 4102: 用户名已存在 |
| 4200-4299 | 用户等级 | 4201: 等级编码已存在 |
| 5000-5999 | 文件模块(预留) | 5001: 上传失败, 5002: 文件大小超限 |
| 6000-6999 | 消息模块(预留) | 6001: 发送失败, 6002: 模板不存在 |
完整枚举值见 Result 统一响应类 → ResultCode 枚举
错误响应示例:
{
"error": 4102,
"message": "用户名已存在",
"code": "USER_INFO_USERNAME_EXISTS"
}
五、Controller 命名与路径映射
5.1 命名规则
| 类型 | Controller 命名 | 路径 | 说明 |
|---|---|---|---|
| 对外业务 | UserController |
/v1/user/users/** |
常规 CRUD |
| 内部调用 | UserInnerController |
/user/inner/** |
Feign 调用 |
| 对外入口 | UserEntryController |
/user/entry/** |
免认证入口 |
| 第三方回调 | PayNotifyController |
/pay/notify/** |
Webhook |
| 后台管理 | UserAdminController |
/v1/user/admin/** |
管理接口 |
5.2 方法命名
| 操作 | 方法名 | HTTP | 路径 |
|---|---|---|---|
| 列表 | list / page |
GET | /{资源} |
| 详情 | getById |
GET | /{资源}/{id} |
| 新增 | add / save |
POST | /{资源} |
| 更新 | update / edit |
PUT | /{资源}/{id} |
| 局部更新 | patch |
PATCH | /{资源}/{id} |
| 删除 | remove / delete |
DELETE | /{资源}/{id} |
| 批量删除 | batchRemove |
DELETE | /{资源}/batch |
| 导出 | export |
GET | /{资源}/export |
| 导入 | import |
POST | /{资源}/import |
六、Swagger 注解规范
6.1 Controller 注解
@Tag(name = "用户管理", description = "用户相关接口")
@RestController
@RequestMapping("/v1/user/users")
public class UserController {
@Operation(summary = "查询用户列表", description = "支持分页、排序、条件查询")
@GetMapping
public Result<PageResult<UserVO>> list(
@Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer page,
@Parameter(description = "每页条数") @RequestParam(defaultValue = "10") Integer size) {
// ...
}
@Operation(summary = "新增用户")
@PostMapping
public Result<Long> add(@RequestBody @Valid UserDTO dto) {
// ...
}
}
6.2 DTO / VO 注解
@Schema(description = "用户新增DTO")
@Data
public class UserDTO {
@Schema(description = "用户名", requiredMode = Schema.RequiredMode.REQUIRED, example = "admin")
@NotBlank(message = "用户名不能为空")
@Size(min = 2, max = 50, message = "用户名长度2-50字符")
private String username;
@Schema(description = "状态 0:禁用 1:启用", example = "1")
private Integer status;
}
七、数据校验规范
7.1 分组校验
public interface AddGroup {} // 新增分组
public interface UpdateGroup {} // 更新分组
7.2 使用示例
@Data
public class UserDTO {
@NotNull(message = "ID不能为空", groups = UpdateGroup.class)
private Long id;
@NotBlank(message = "用户名不能为空", groups = {AddGroup.class, UpdateGroup.class})
private String username;
}
// Controller
@PostMapping
public Result<Long> add(@RequestBody @Validated(AddGroup.class) UserDTO dto) {
// 新增
}
@PutMapping("/{id}")
public Result<Void> update(@RequestBody @Validated(UpdateGroup.class) UserDTO dto) {
// 更新
}
八、Feign 接口规范
8.1 接口定义
/**
* 远程用户服务
*/
@Headers("INTERNAL_REQUEST: INTERNAL")
@FeignClient(
contextId = "remoteUserService",
value = "${feign.providers.user:rui-service-user}",
path = "/user/inner"
)
public interface RemoteUserService {
@GetMapping("/auth/loadByUsername/{username}")
Result<Map<String, Object>> loadUser(@PathVariable String username);
}
8.2 调用规范
@Service
@RequiredArgsConstructor
public class UserRemoteService {
private final RemoteUserService remoteUserService;
public UserVO getUserById(Long userId) {
Result<UserVO> result = remoteUserService.getById(userId);
if (result.isSuccess()) {
return result.getData();
}
throw new BizException(result.getError(), result.getMessage());
}
}
九、文件上传接口规范
9.1 单文件上传
POST /v1/file/files/upload
Content-Type: multipart/form-data
file: [二进制文件]
module: user
bizId: 1001
响应:
{
"code": 200,
"msg": "上传成功",
"data": {
"fileId": "123456",
"fileName": "avatar.jpg",
"fileUrl": "https://oss.example.com/avatar/123456.jpg",
"fileSize": 102400
}
}
9.2 多文件上传
POST /v1/file/files/batchUpload
Content-Type: multipart/form-data
files: [文件1, 文件2, 文件3]
module: user
十、导出接口规范
10.1 Excel 导出
GET /v1/user/users/export?username=admin&status=1
Accept: application/vnd.ms-excel
响应:
Content-Type: application/vnd.ms-excel
Content-Disposition: attachment; filename="用户列表_20240101.xlsx"
10.2 CSV 导出
GET /v1/user/users/export?format=csv
Accept: text/csv
十一、WebSocket 接口规范(预留)
ws://gateway:9300/ws/{模块}/{topic}
示例:
ws://localhost:9300/ws/msg/notification # 消息通知
ws://localhost:9300/ws/monitor/metrics # 实时监控
十二、接口文档生成
12.1 配置 SpringDoc
springdoc:
swagger-ui:
path: /swagger-ui.html
enabled: true
api-docs:
path: /v3/api-docs
enabled: true
group-configs:
- group: 用户服务
display-name: 用户服务 API
paths-to-match: /v1/user/**
- group: 系统服务
display-name: 系统服务 API
paths-to-match: /v1/system/**
12.2 访问地址
Swagger UI 页面
http://localhost:9300/swagger-ui.html # 网关聚合文档
http://localhost:9301/swagger-ui.html # 认证服务文档
http://localhost:9302/swagger-ui.html # 系统服务文档
http://localhost:9303/swagger-ui.html # 用户服务文档
http://localhost:9601/swagger-ui.html # 收银服务文档
Knife4j 增强 UI(推荐)
http://localhost:9300/doc.html # 网关聚合文档
http://localhost:9301/doc.html # 认证服务文档
http://localhost:9302/doc.html # 系统服务文档
http://localhost:9303/doc.html # 用户服务文档
http://localhost:9601/doc.html # 收银服务文档
OpenAPI JSON 接口
http://localhost:9300/v3/api-docs # 网关聚合 API 文档
http://localhost:9301/v3/api-docs # 认证服务 API 文档
http://localhost:9302/v3/api-docs # 系统服务 API 文档
http://localhost:9303/v3/api-docs # 用户服务 API 文档
http://localhost:9399/v3/api-docs # 聚合启动器 API 文档(开发调试)
http://localhost:9601/v3/api-docs # 收银服务 API 文档
十三、文件存储服务(rui-service-storage)
服务定位:独立微服务(9400 端口 / 聚合启动器 9399),所有业务模块共用一个上传入口,通过
bizType区分业务场景。 前端组件:<RuiUpload>(rui-frontend#5)。
13.1 上传文件
POST /storage/upload
Content-Type: multipart/form-data
表单参数
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
file |
File | ✅ | 文件本体 |
bizType |
string | ✅ | 业务类型,匹配 ^[A-Z][A-Z0-9_]{0,50}$ |
storage |
string | ❌ | aliyun / tencent / local;不传走默认 |
fileName |
string | ❌ | 固定存储名,匹配 ^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$ |
extract |
bool | ❌ | true 时若为 .zip 自动解压为多文件入库 |
响应:data: SysFileUploadVO[](统一为数组,单文件上传也是长度 1)。
{
"code": 0,
"message": "ok",
"data": [
{
"id": 1234567890,
"name": "abc123.jpg",
"originalName": "photo.jpg",
"path": "user-avatar/2026/06/abc123.jpg",
"url": "https://bucket.oss-cn-shanghai.aliyuncs.com/user-avatar/2026/06/abc123.jpg",
"size": 12345,
"contentType": "image/jpeg",
"storageType": "ALIYUN",
"bizType": "USER_AVATAR"
}
]
}
13.2 查询文件详情
GET /storage/file/{id}
13.3 分页查询
GET /storage/file/page?pageNum=1&pageSize=20&bizType=SYS_APP_CERT
13.4 删除文件
DELETE /storage/file/{id}
物理删除对象存储文件 + 软删 sys_file 记录。
13.5 已知 bizType
| bizType | 限制 | 用途 |
|---|---|---|
COMMON |
10MB | 通用 |
SYS_APP_CERT |
5MB / pem,crt,key,p12 | 第三方应用证书 |
USER_AVATAR |
2MB / jpg,jpeg,png,webp | 用户头像 |
CMS_BANNER |
5MB / jpg,jpeg,png,webp,gif | CMS 轮播图 |
新业务模块直接传新字符串(如 ORDER_PROOF),后端 yml 配 rui.file.biz-types.<新>.max-size / allowed-extensions 即可,前端不需要等后端发版。
13.6 前端使用示例
<script setup>
import RuiUpload from '@/components/RuiUpload/RuiUpload.vue'
import type { UploadResult } from '@/service/system/storageService'
const certFiles = ref<UploadResult[]>([])
</script>
<template>
<RuiUpload
v-model="certFiles"
biz-type="SYS_APP_CERT"
:max-size="20"
accept=".pem,.crt,.key,.p12,.zip"
:extract="false"
/>
</template>
十四、Postman / APIFox 集合规范
13.1 目录结构
睿核科技通用平台
├── 01-认证中心
│ ├── 获取Token
│ ├── 刷新Token
│ └── 退出登录
├── 02-用户中心
│ ├── 用户管理
│ ├── 等级管理
│ └── 用户查询
├── 03-系统管理
│ ├── 租户管理
│ ├── 菜单管理
│ ├── 角色管理
│ ├── 字典管理
│ └── 参数配置
├── 04-文件管理
│ ├── 文件上传
│ └── 文件下载
└── 99-内部接口(Feign)
├── 用户服务
└── 系统服务
13.2 环境变量
{
"baseUrl": "http://localhost:9300",
"token": "{{login_response_token}}",
"tenantId": "1"
}
十四、接口变更管理
14.1 变更类型
| 类型 | 说明 | 版本处理 |
|---|---|---|
| 新增接口 | 新增资源/功能 | 当前版本可用 |
| 新增字段 | 请求/响应增加字段 | 当前版本可用(兼容) |
| 废弃字段 | 字段标记 deprecated | 当前版本可用,下版本移除 |
| 废弃接口 | 接口标记 deprecated | 保留至少2个版本后移除 |
| 破坏性变更 | 字段删除/类型变更 | 升级版本号(v1 → v2) |
14.2 版本迭代策略
v1.0 —— 初始版本
v1.1 —— 新增字段(兼容)
v1.2 —— 新增接口(兼容)
v2.0 —— 破坏性变更(不兼容)
文档版本: v1.0 创建日期: 2026-05-28 适用范围: 睿核科技通用平台框架所有 RESTful API