Moment For Technology

How to design the API interface for uniform format return?

Posted on June 24, 2022, 2:58 a.m. by Amy Smith
Category: The back-end Tag: The back-end api

The front and back interfaces interact

As we all know, the front end usually obtains data through the interface provided by the background to complete the rendering of the front end page. The front end can be PC end, M end, small program, APP and so on.

I'll cut the crap here. That's not the point.

Interface return value convention

Return value specification

  • Set the returned HTTP response status code.
  • When an error occurs, the error code and description of Response Body need to be set.

Right back

HTTP Response status code, set to 200, Response Body structure is the returned data structure.

Error return

HTTP response status code, do not set to 200! Comply with RFC standards.

Type Failure struct {Code int 'json:" Code "' // business Code Message string 'json:" Message "' // Description}Copy the code

Uniformly define error codes

Error code specification

  • Define error codes in one file;
  • The error code length is 5 bits.

What level of error is the first bit? For example, 1 indicates a system-level error, and 2 indicates a service module error. Nine error levels can be marked.

Which module do bits 2 and 3 indicate the error? For example, 01 is the user module, 02 is the order module, 99 modules can be marked.

What is the error in digits 4 and 5? For example, 01 indicates that the mobile phone number is invalid, and 02 indicates that the verification code is incorrect. 99 errors can be marked.

How to use the Controller layer?

Right back

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

Error return

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

return 
Copy the code

Detailed code implementation

Error code

  • Error code encapsulation: github.com/xinliangnot...
  • Define error code: github.com/xinliangnot...

Controller

conclusion

The above code for your reference, there is room for optimization, welcome to use and put forward valuable comments.

thinking

  • 1. How to secure signature verification when external interfaces are provided?
  • 2. How to design the idempotency of the interface?
  • 3. How to uniformly desensitize the returned data for sensitive data?
  • 4. How to design interface logs to facilitate rapid error location during interface joint debugging?
  • 5. How to generate interface documents automatically? Heard of Swagger and don't know how to use it?

If you have any doubts or doubts about the above questions, come to my planet to discuss.

Search
About
mo4tech.com (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.