当前位置:网站首页>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 ”
边栏推荐
- [digital analog] source code of MATLAB allcycles() function (not available before 2021a)
- Basic idea of counting and sorting
- DFS and BFS concepts and practices +acwing 842 arranged numbers (DFS) +acwing 844 Maze walking (BFS)
- Common Oracle SQL statements
- C语言中函数指针与指针函数
- Vscode 如何使用内置浏览器?
- In depth analysis of kubebuilder
- Markdown编辑器
- Read of shell internal value command
- npm ERR! 400 Bad Request - PUT xxx - “devDependencies“ dep “xx“ is not a valid dependency name
猜你喜欢
Local tool [Navicat] connects to remote [MySQL] operation
offer如何选择该考虑哪些因素
九章云极DataCanvas公司获评36氪「最受投资人关注的硬核科技企业」
Tree map: tree view - draw covid-19 array diagram
Have you got the same "artifact" of cross architecture development praised by various industry leaders?
01机器学习相关规定
Time complexity & space complexity
当 Knative 遇见 WebAssembly
Flask项目使用flask-socketio异常:TypeError: function() argument 1 must be code, not str
Why do many people misunderstand technical debt
随机推荐
What is Web3
If you ask me about R code debugging, I will tell you head, STR, help
[Android kotlin collaboration] use coroutinecontext to realize the retry logic after a network request fails
Lessons and thoughts of the first SQL injection
JS variable plus
程序员上班摸鱼,这么玩才高端!
Station B boss used my world to create convolutional neural network, Lecun forwarding! Burst the liver for 6 months, playing more than one million
What work items do programmers hate most in their daily work?
The worse the AI performance, the higher the bonus? Doctor of New York University offered a reward for the task of making the big model perform poorly
深入解析Kubebuilder
leetcode 53. Maximum subarray maximum subarray sum (medium)
Introduction to namespace Basics
Factor analysis r practice (with R installation tutorial and code)
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
两个div在同一行,两个div不换行「建议收藏」
Lecture 3 of "prime mover x cloud native positive sounding, cost reduction and efficiency enhancement lecture" - kubernetes cluster utilization improvement practice
什么是Web3
Flex layout and usage
《原动力 x 云原生正发声 降本增效大讲堂》第三讲——Kubernetes 集群利用率提升实践
如何设计 API 接口,实现统一格式返回?