签入版本

This commit is contained in:
2026-10-08 17:50:29 +08:00
parent 809750b47e
commit e213a9b31d
444 changed files with 39366 additions and 37533 deletions
@@ -1,7 +1,7 @@
# 12.1 API 响应规范
:::tip 概述
所有接口返回统一的 JSON 结构,前端可据此判断请求结果。成功响应 `code=0`,失败响应 `code=1`(或 401/403/404/422)。
所有接口返回统一的 JSON 结构,前端可据此判断请求结果。成功响应 `code=0`,失败响应 `code=1`(或 401/403/404/422/500)。HTTP 状态码默认 200,仅 403 例外。详细机制见 [8.1 统一响应格式](/zh/api-spec/response.html)。
:::
## 统一格式
@@ -67,7 +67,7 @@ interface ApiResponse {
| `code` | number | 状态码,0=成功 |
| `ok` | boolean | 是否成功 |
| `msg` | string | 提示信息 |
| `data` | any | 响应数据,失败时通常为 null |
| `data` | any | 响应数据,失败时通常为 null 或错误明细 |
| `data.records` | array | 分页数据列表 |
| `data.total` | number | 总记录数 |
| `data.size` | number | 每页条数 |
@@ -84,32 +84,33 @@ interface ApiResponse {
| `user_name` | `userName` |
| `is_delete` | `isDelete` |
可通过 `config/api.php` 的 `camel_snake_convert` 配置关闭。
可通过 `config/api.php` 的 `camel_snake_convert`(环境变量 `API_CAMEL_SNAKE_CONVERT`)关闭;需要单个接口原样返回时用 `Result::success($data, $msg, true)`。
## 后端构造方式
```php
// Controller 中
return $this->success($data, '操作成功'); // 成功
return $this->success(['id' => $id], '添加成功'); // 成功(带数据)
return $this->fail('用户名已存在'); // 失败
return $this->_page($result); // 分页
// Controller 中(基类方法,推荐)
return $this->success($data, '操作成功'); // 成功
return $this->success(['id' => $id], '添加成功'); // 成功(带数据)
return $this->fail('用户名已存在'); // 失败(code 默认 1)
return $this->paginate($pageListResult); // 分页(records/total/current/size/pages)
return $this->_page($service, $where); // 分页(直接传 Service,内部调用 pageList)
```
```php
// Result 类直接调用
// Result 类直接调用(app/Support/Result.php)
Result::success($data, $msg);
Result::page($records, $total, $current, $size);
Result::page($records, $total, $current, $size, $pages = null); // 分页响应
Result::fail($msg, $code);
Result::unauthorized($msg); // 401
Result::forbidden($msg); // 403
Result::unauthorized($msg); // 401(HTTP 200 + body code)
Result::forbidden($msg); // 403(HTTP 403)
Result::notFound($msg); // 404
Result::validateError($errors); // 422 参数验证失败
```
### validateError 示例
`Result::validateError()` 用于参数验证失败场景,HTTP 状态码为 422,`data` 字段返回具体错误明细,便于前端逐字段提示:
`Result::validateError()` 用于参数验证失败场景,`code=422`,`data` 字段返回具体错误明细,便于前端逐字段提示:
```php
// 直接传字符串
@@ -117,8 +118,8 @@ return Result::validateError('用户名不能为空');
// 传数组,包含多个字段错误
return Result::validateError([
'username' => '用户名不能为空',
'email' => '邮箱格式不正确',
'username' => ['用户名不能为空'],
'email' => ['邮箱格式不正确'],
]);
```
@@ -128,8 +129,8 @@ return Result::validateError([
"ok": false,
"msg": "参数验证失败",
"data": {
"username": "用户名不能为空",
"email": "邮箱格式不正确"
"username": ["用户名不能为空"],
"email": ["邮箱格式不正确"]
}
}
```
```