Files
rxthinkcmf-wiki/RXThinkCMF_Laravel13_AntdVue/zh/standards/api-response.md
T
2026-09-29 10:14:04 +08:00

135 lines
2.9 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)。
:::
## 统一格式
```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` 配置关闭。
## 后端构造方式
```php
// Controller 中
return $this->success($data, '操作成功'); // 成功
return $this->success(['id' => $id], '添加成功'); // 成功(带数据)
return $this->fail('用户名已存在'); // 失败
return $this->_page($result); // 分页
```
```php
// Result 类直接调用
Result::success($data, $msg);
Result::page($records, $total, $current, $size);
Result::fail($msg, $code);
Result::unauthorized($msg); // 401
Result::forbidden($msg); // 403
Result::notFound($msg); // 404
Result::validateError($errors); // 422 参数验证失败
```
### validateError 示例
`Result::validateError()` 用于参数验证失败场景,HTTP 状态码为 422,`data` 字段返回具体错误明细,便于前端逐字段提示:
```php
// 直接传字符串
return Result::validateError('用户名不能为空');
// 传数组,包含多个字段错误
return Result::validateError([
'username' => '用户名不能为空',
'email' => '邮箱格式不正确',
]);
```
```json
{
"code": 422,
"ok": false,
"msg": "参数验证失败",
"data": {
"username": "用户名不能为空",
"email": "邮箱格式不正确"
}
}
```