当前位置:网站首页>How to design API interface and realize unified format return?
How to design API interface and realize unified format return?
2022-07-07 04:57:00 【androidstarjack】
Click on the top “ Terminal R & D department ”
Set to “ Star standard ”, Master more database knowledge with you source : The headline number 【 Old customers talk about technology 】
Preface
On the mobile Internet , Distributed 、 Micro services are popular today , Now most of the projects adopt the microservice framework , Front and rear end separation mode ,( Digression : The responsibilities of the front and back end are more and more clear , Now the front end is called the big front end , The technology stack and the ecosystem are very mature ; Back end people used to look down on front end people , Now the back-end staff should have a new understanding of the front-end , The front end is very systematic ).
The general overall architecture of the system is as follows :

It should be noted that , Some of them will reply and say , This structure is too simple , too low 了 , What gateway , Cache , Message middleware , None . Because this article mainly introduces API Interface , So let's focus on , The other modules are supplemented by friends .
Interface interaction
Front end and back end interact , The front end requests URL route , And pass in the relevant parameters , The backend server receives the request , Conduct business processing , Return data to the front end .
in the light of URL The path of restful style , As well as the requirements of the public request header for the incoming parameters ( Such as :app_version,api_version,device etc. ), I won't introduce it here , Friends can learn about , It's easier .
How does the back-end server return data to the front-end ?
Returns the format
The back end returns to the front end. We usually use JSON Body style , The definition is as follows :
{
# Return status code
code:integer,
# Return message description
message:string,
# Return value
data:object
}CODE Status code
code Return status code , What do you need when you are developing , Just add something .
If the interface wants to return the user permission exception , Let's add a status code to 101 Well , Another data parameter exception will be added next time , Just one more 102 The status code . In this way, the business can be satisfied as usual , But the status code is too messy
We should be able to refer to HTTP Status code returned by the request
: Here is a common HTTP Status code :
200 - The request is successful
301 - resources ( Web page, etc ) Be permanently transferred to another URL
404 - Requested resources ( Web page, etc ) non-existent
500 - Internal server error 
We can refer to such a design , The advantage of this is to classify the error type into a certain range , If the interval is not enough , Can be designed as 4 digit .
#1000~1999 Interval indicates parameter error
#2000~2999 Interval indicates user error
#3000~3999 The interval indicates that the interface is abnormal So the front-end developers get the return value , According to the status code, we can know , Probably something wrong , According to message Related information description , Can quickly locate .
Message
This field is relatively easy to understand , When something goes wrong , How to give friendly tips . The general design is and code State codes are designed together , Such as

Then define... In the enumeration , Status code

The status code and the information will correspond one by one , It's easier to maintain .
Data
Return data body ,JSON Format , According to different business and different JSON body .
We are going to design a return body class Result

Control layer Controller
We will be in controller Layer handles business requests , And back to the front end , With order Take the order for example

We see in getting order After object , We use Result Construction method for package assignment , Then go back . Did you guys find out , How to construct such a package is not very troublesome , We can optimize .
To beautify
We can do it in Result Class , Add static methods , A look at will understand

Let's transform it Controller

Is the code simpler , It's also beautiful .
Elegant optimization
We can see it above Result Class with static methods , Make the business process code simple . But did you find any problems like this :
1、 The return of each method is Result Encapsulated object , There is no business meaning
2、 In the business code , When we succeed, we call Result.success, Exception error call Result.failure. Is it a lot more than
3、 The above code , Judge id Is it null, In fact, we can use hibernate validate Make a check , There is no need to make a judgment in the method body .
Our best way to go directly back to real business objects , It's better not to change the way of business before , Here's the picture

This code is the same as our usual , Very intuitive , Go straight back to order object , Is this perfect . What is the implementation plan ?
Implementation scheme
Do you have some ideas on how to realize it , In the process , We need to do a few things
1、 Define an annotation @ResponseResult, Indicates that the returned value of this interface needs to be wrapped
2、 Intercept request , Determine whether the request needs to be @ResponseResult annotation
3、 The core step is to implement the interface ResponseBodyAdvice and @ControllerAdvice, Determine whether the return value of the package is needed , if necessary , Just put Controller The return value of the interface is rewritten .
Annotation class
Used to mark the return value of a method , Do you need packing

Interceptor
Intercept request , Whether the value returned by this request needs to be wrapped , In fact, when it's running , analysis @ResponseResult annotation

The core idea of this code , To get this request , Whether return value packing is needed , Set a property tag .
Rewrite the return body

The above code is to determine whether a return value wrapper is needed , Pack it directly if you need it . Here we only deal with normal successful packaging , What to do if the method body reports an exception ? Handling exceptions is also relatively simple , Just judge body Is it an exception class .

How to do global exception handling , The space for , I won't introduce you here , As long as the thinking is clear , Just remodel yourself .
rewrite Controller

Add... To the controller class or method body @ResponseResult annotation , So you ok 了 , Easy . The design idea returned here is completed , Is it simple , Elegant .
Is there any other optimization space for this scheme , Of course there are . Such as : Every request has to reflect , Whether the requested method needs to be wrapped , In fact, we can make a cache , You don't need to parse every time . Of course, we understand the overall thinking , You can expand on this basis , If there is harvest , Please help forward ~
Write it at the end
You can leave a message below to discuss what you don't understand , You can also ask me by private message. I will reply after seeing it . Finally, if the article is helpful to you, please remember to give me a like , Pay attention and don't get lost
@ Terminal R & D department
Fresh dry goods are shared every day !
reply 【idea Activate 】 You can get idea How to activate
reply 【Java】 obtain java Relevant video tutorials and materials
reply 【SpringCloud】 obtain SpringCloud Many relevant learning materials
reply 【python】 Get the full set 0 Basics Python Knowledge Manual
reply 【2020】 obtain 2020java Related interview questions tutorial
reply 【 Add group 】 You can join the technical exchange group related to the terminal R & D department
Read more
use Spring Of BeanUtils front , I suggest you understand these pits first !
lazy-mock , A lazy tool for generating backend simulation data
In Huawei Hongmeng OS Try some fresh food , My first one “hello world”, take off !
The byte is bouncing :i++ Is it thread safe ?
One SQL Accidents caused by , Colleagues are fired directly !!
Too much ! Check Alibaba cloud ECS Of CPU Incredibly reach 100%
a vue Write powerful swagger-ui, A little show ( Open source address attached )
Believe in yourself , Nothing is impossible , Only unexpected, not only technology is obtained here !
If you like, just give me “ Looking at ”边栏推荐
- Detect when a tab bar item is pressed
- How does vscade use the built-in browser?
- 日常工作中程序员最讨厌哪些工作事项?
- Function pointer and pointer function in C language
- Gavin teacher's perception of transformer live class - rasa project actual combat e-commerce retail customer service intelligent business dialogue robot microservice code analysis and dialogue experim
- Introduction to the PureMVC series
- Up to 5million per person per year! Choose people instead of projects, focus on basic scientific research, and scientists dominate the "new cornerstone" funded by Tencent to start the application
- offer如何选择该考虑哪些因素
- Structure actual training camp | after class homework | module 6
- Zhou Yajin, a top safety scholar of Zhejiang University, is a curiosity driven activist
猜你喜欢

How to package the parsed Excel data into objects and write this object set into the database?

Oracle - views and sequences

Pointer and array are input in function to realize reverse order output

【线段树实战】最近的请求次数 + 区域和检索 - 数组可修改+我的日程安排表Ⅰ/Ⅲ

Break the memory wall with CPU scheme? Learn from PayPal to expand the capacity of aoteng, and the volume of missed fraud transactions can be reduced to 1/30

Flask项目使用flask-socketio异常:TypeError: function() argument 1 must be code, not str

Intel David tuhy: the reason for the success of Intel aoten Technology

树与图的深度优先遍历模版原理

九章云极DataCanvas公司摘获「第五届数字金融创新大赛」最高荣誉!

【736. Lisp 语法解析】
随机推荐
Programmers go to work fishing, so play high-end!
Oracle -- 视图与序列
Kivy tutorial of setting the size and background of the form (tutorial includes source code)
JS also exports Excel
Function pointer and pointer function in C language
Break the memory wall with CPU scheme? Learn from PayPal to expand the capacity of aoteng, and the volume of missed fraud transactions can be reduced to 1/30
Tiktok may launch an independent grass planting community platform: will it become the second little red book
leetcode 53. Maximum Subarray 最大子数组和(中等)
Vscode 如何使用内置浏览器?
Flask project uses flask socketio exception: typeerror: function() argument 1 must be code, not str
Flex layout and usage
指针与数组在函数中输入实现逆序输出
Jetson nano配置pytorch深度学习环境//待完善
01 machine learning related regulations
Analyse approfondie de kubebuilder
How to package the parsed Excel data into objects and write this object set into the database?
JDBC link Oracle reference code
树与图的深度优先遍历模版原理
浙江大学周亚金:“又破又立”的顶尖安全学者,好奇心驱动的行动派
一图看懂!为什么学校教了你Coding但还是不会的原因...