In this series of , we will show you how to access the database in Spring Boot, and this time we will go deeper and standardize the format of the data returned by the Restful service interface.
Uniform format of the return value
The standardized and uniform data interface format is conducive to the reuse of server-side and client-side code, and enhances the maintainability of the system. In practice, for Restful service interfaces, the following data format is generally recommended:
- Success Flag (succ) - Defines whether the call was successful on the business, technically successfully handed over to the HTTP return value.
- (Error) Return code - Typically used in the event of a Business error, returns an error code.
- (Error) Message (msg) - Typically used in the event of a Business error, it returns a localized error message for the client to display itself.
- Returned data - The data returned during a normal call, which can be simple data or composite data, such as objects, arrays, etc.
Based on the above design, the implementation code in Java is as follows:
1 |
|
Put this class into the api.vo package. The class uses @Data annotations to generate the property’s get/set method and @Builder to establish the corresponding constructor.
Retrofitting of new backlog interfaces
In the original new interface implementation, the code is:
1 | "/todo") ( |
To change the uniform way, you need to change the return value of the function to: ApiResult, and assign the value of ApiResult according to the execution result of todoBiz.addTodo. The modified code is as follows:
1 | "/todo") ( |
Here, BizException is a custom exception class that inherits from RuntimeException, Note: Lines 4, 6, and 10 are all template-style code that can be summarized as:
1 | ApiResult.ApiResultBuilder builder = ApiResult.builder().succ(false).build().toBuilder(); |
Let’s give this template a name: API Process Template, and in the following courses, we will teach you to abstract the template to simplify development.
After modifying it, run the program and send a post request using PostMan or curl simulation, with the body parameter set to:
1 | {"title":"task 1", "desc":"desc of task 1"} |
The server returns:
1 | { |
The description is successful, and when you view the database, you can see that the data has been inserted into the data table.
Retrofitting the Get To-Do Interface
In the original getTodoList method, the code is:
1 | "/todo") ( |
Now, instead, we’re going to get the to-dos in the database and transform that approach with API process templates.
1 | "/todo") ( |
After modifying it, run the program and access
1 | http://localhost:8080/todo |
directly from the browser, the result is:
1 | {"succ":true,"code":null,"msg":null,"data":[{"id":1,"title":"task 1","desc":"desc of task 1"}]} |
Next
In next article, you will learn how to handle data checksum errors.