Files
rxthinkcmf-wiki/RXThinkCMF_Laravel13_NaiveVue/zh/standards/api-response.md
T
2026-10-08 17:50:29 +08:00

137 lines
3.5 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.
# 12.1 API 响应规范
:::tip 概述
所有接口返回统一的 JSON 结构,前端可据此判断请求结果。成功响应 `code=0`,失败响应 `code=1`(或 401/403/404/422/500)。HTTP 状态码默认 200,仅 403 例外。详细机制见 [8.1 统一响应格式](/zh/api-spec/response.html)。
:::
## 统一格式
```typescript
interface ApiResponse {
code: number; // 状态码:0=成功,其他=失败
ok: boolean; // 是否成功
msg: string; // 提示信息
data: any; // 响应数据
}
```
## 成功响应
```json
{
"code": 0,
"ok": true,
"msg": "操作成功",
"data": {
"id": 1,
"username": "admin",
"createTime": "2026-01-01 00:00:00"
}
}
```
## 分页响应
```json
{
"code": 0,
"ok": true,
"msg": "操作成功",
"data": {
"records": [
{ "id": 1, "username": "admin" }
],
"total": 100,
"size": 20,
"current": 1,
"pages": 5
}
}
```
## 失败响应
```json
{
"code": 1,
"ok": false,
"msg": "用户名已存在",
"data": null
}
```
## 字段说明
| 字段 | 类型 | 说明 |
|------|------|------|
| `code` | number | 状态码,0=成功 |
| `ok` | boolean | 是否成功 |
| `msg` | string | 提示信息 |
| `data` | any | 响应数据,失败时通常为 null 或错误明细 |
| `data.records` | array | 分页数据列表 |
| `data.total` | number | 总记录数 |
| `data.size` | number | 每页条数 |
| `data.current` | number | 当前页码 |
| `data.pages` | number | 总页数 |
## 驼峰自动转换
响应数据自动从 snake_case 转为 camelCase:
| 数据库字段 | 响应字段 |
|-----------|---------|
| `create_time` | `createTime` |
| `user_name` | `userName` |
| `is_delete` | `isDelete` |
可通过 `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('用户名已存在'); // 失败(code 默认 1)
return $this->paginate($pageListResult); // 分页(records/total/current/size/pages)
return $this->_page($service, $where); // 分页(直接传 Service,内部调用 pageList)
```
```php
// Result 类直接调用(app/Support/Result.php)
Result::success($data, $msg);
Result::page($records, $total, $current, $size, $pages = null); // 分页响应
Result::fail($msg, $code);
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()` 用于参数验证失败场景,`code=422`,`data` 字段返回具体错误明细,便于前端逐字段提示:
```php
// 直接传字符串
return Result::validateError('用户名不能为空');
// 传数组,包含多个字段错误
return Result::validateError([
'username' => ['用户名不能为空'],
'email' => ['邮箱格式不正确'],
]);
```
```json
{
"code": 422,
"ok": false,
"msg": "参数验证失败",
"data": {
"username": ["用户名不能为空"],
"email": ["邮箱格式不正确"]
}
}
```