Files
rui-docs/standards/API设计规范.md
T

530 lines
13 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 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`
- 模糊匹配:字段名加后缀 `_like` `username_like=admin`
- 范围查询:字段名加后缀 `_start` / `_end` `createdAt_start=2024-01-01`
- 多值查询:字段名加后缀 `_in` `status_in=1,2`
---
## 四、响应规范
### 4.1 统一响应格式
```json
{
"code": 200,
"msg": "操作成功",
"data": {}
}
```
### 4.2 分页响应格式
```json
{
"code": 200,
"msg": "操作成功",
"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 错误码规范
| 区间 | 模块 | 示例 |
|------|------|------|
| 1000-1999 | 通用 | 1001: 参数校验失败, 1002: 资源不存在 |
| 2000-2999 | 用户模块 | 2001: 用户名已存在, 2002: 密码错误 |
| 3000-3999 | 系统模块 | 3001: 字典不存在, 3002: 配置错误 |
| 4000-4999 | 认证模块 | 4001: Token 过期, 4002: 无权访问 |
| 5000-5999 | 文件模块 | 5001: 上传失败, 5002: 文件过大 |
| 6000-6999 | 消息模块 | 6001: 发送失败, 6002: 模板不存在 |
**错误响应示例**
```json
{
"code": 2001,
"msg": "用户名已存在",
"data": null
}
```
---
## 五、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 注解
```java
@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 注解
```java
@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 分组校验
```java
public interface AddGroup {} // 新增分组
public interface UpdateGroup {} // 更新分组
```
### 7.2 使用示例
```java
@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 接口定义
```java
/**
* 远程用户服务
*/
@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 调用规范
```java
@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.getCode(), result.getMsg());
}
}
```
---
## 九、文件上传接口规范
### 9.1 单文件上传
```
POST /v1/file/files/upload
Content-Type: multipart/form-data
file: [二进制文件]
module: user
bizId: 1001
```
**响应**
```json
{
"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
```yaml
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 文档
```
---
## 十三、Postman / APIFox 集合规范
### 13.1 目录结构
```
睿核科技通用平台
├── 01-认证中心
│ ├── 获取Token
│ ├── 刷新Token
│ └── 退出登录
├── 02-用户中心
│ ├── 用户管理
│ ├── 等级管理
│ └── 用户查询
├── 03-系统管理
│ ├── 租户管理
│ ├── 菜单管理
│ ├── 角色管理
│ ├── 字典管理
│ └── 参数配置
├── 04-文件管理
│ ├── 文件上传
│ └── 文件下载
└── 99-内部接口(Feign
├── 用户服务
└── 系统服务
```
### 13.2 环境变量
```json
{
"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