一种好用的接口请求和响应格式规范,基于Google Json Style

一种好用的接口请求和响应格式规范,基于Google Json Style


2021-11-01
development, frontend, backend, api

简述

  1. 基于较为流行的谷歌 json 风格 google json style
    1. 英文 https://google.github.io/styleguide/jsoncstyleguide.xml
    2. 中文 https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md
  2. 所有字段驼峰命名,接口使用:get post
    1. get 获取数据
    2. post 更新数据
  3. post:请求 body 数据使用 application/json, 不使用 FormData;
  4. 响应成功,仅返回 data;响应错误,仅返回 error。如果data和error同时出现,则error对象优先。
  5. HTTP_STATUS 始终200, 如果非 200,则说明出现错误,提示“服务器异常”。

POST 请求:

1
2
3
4
5
6
7
8
    {
        "method": "thread.review.list 可简化",
        "params": {
            "id": 100,
            "type": 1
        }
    }
    

接口响应:

正确响应

  1. 列表响应 items
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
    {
        "apiVersion": "2.0",
        "method": "thread.review.list",
        "data": {
            "tableHeader": {
                "id": "ID",
                "name": "标题"
            },
            "items": [
                {
                    "id": 10021,
                    "name": "第一个帖子"
                }
            ],
            "pagination": {
                "pageIndex": 50,
                "totalPages": 10,
                "itemsPerPage": 50,
                "totalItems": 495,
                "currentItemCount": 45
            }
        }
    }
    
  1. 详细数据响应 item
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
    {
        "apiVersion": "2.0",
        "method": "thread.review.detail",
        "data": {
            "item": {
                "id": 10031,
                "name": "第一个帖子"
            }
        }
    }
    

发生错误

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
    
    {
        "apiVersion": "2.0",
        "method": "thread.review.list",
        "error": {
            "code": 400,
            "message": "数据异常",
            "errors": [
                {
                    "domain": "Calendar",
                    "reason": "ResourceNotFoundException",
                    "message": "File Not Found"
                }
            ]
        }
    }
    

错误处理

  1. 响应存在 error 则说明发生错误,error 优先级高于 data
  2. error.message 始终 toast 提示
  3. 特殊逻辑处理根据 error.code 进行判断
  4. HTTP_STATUS 始终200, 如果非 200,则说明出现错误,提示“服务器异常”
  5. 调用接口成功响应,提示文案由前端处理
  6. 业务中的特殊逻辑,在 data 返回处理

特殊 error.code 列表

见仁见智

逻辑 error.code error.message 备注
跳转到登录页 10000100 登录失效,请重新登录
刷新页面 10000101 -
跳转到指定404页面 10000102 -

See Also

沪ICP备2022013452号-1