How to design API interface to realize uniform format return?

Time:2021-7-29

Front and rear interface interaction

As we all know, the front end usually obtains data through the interface provided by the background to complete the rendering of front-end pages. The front end can be PC, m, applet, app, etc.

No more nonsense here. That’s not the point.

Interface return value Convention

Return value specification

  • Set the returned HTTP response status code;
  • When an error occurs, it is necessary to set the error code and description information of the response body;

Correct return

The HTTP response status code is set to 200, and the response body structure is the returned data structure.

Error return

HTTP response status code, do not set to 200! RFC standards to be followed.

//Structure returned on failure error
type Failure struct {
    Code Int ` JSON: "code" ` // business code
    Message string ` JSON: "message" ` // description
}

Unified definition error code

Error code specification

  • Uniformly define error codes in one file;
  • The length of error code is 5 bits;

What level of error does the first digit indicate? For example, 1 is a system level error, 2 is a business module error, and 9 error levels can be marked.

Bits 2 and 3 indicate which module is the error? For example: 01 is the user module, 02 is the order module, and 99 modules can be marked.

The 4th and 5th digits indicate what is the specific error? For example, 01 indicates that the mobile phone number is illegal, 02 indicates that the verification code is entered incorrectly, and 99 errors can be marked.

How to use the controller layer?

Correct return

res := new(createResponse)
res.Id = 1
ctx.Payload(res)

Error return

c.AbortWithError(errno.NewError(
    http.StatusBadRequest,
    code.AdminCreateError,
    code.Text(code.AdminCreateError)).WithErr(err),
)

return 

Detailed code implementation

Error code

Controller

summary

The above code is for your reference and there is room for optimization. You are welcome to use and put forward your valuable opinions.

Problem thinking

  • 1. How to perform secure signature verification when providing external interfaces?
  • 2. How to design the idempotency of the interface?
  • 3. How to uniformly desensitize the returned data?
  • 4. How to design the interface log to facilitate rapid error location during interface joint commissioning?
  • 5. How to generate interface documents automatically? I’ve heard of swagger and don’t know how to use it?

If you are confused or uncertain about the above problems, come to my planet to exchange and discuss,https://t.zsxq.com/iIUVVnA