How to build Rest Service with Spring Boot - A Step by Step Tutorial for Beginner - 3

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:

  1. Success Flag (succ) - Defines whether the call was successful on the business, technically successfully handed over to the HTTP return value.
  2. (Error) Return code - Typically used in the event of a Business error, returns an error code.
  3. (Error) Message (msg) - Typically used in the event of a Business error, it returns a localized error message for the client to display itself.
  4. 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
2
3
4
5
6
7
8
9
10
@Data
@Builder(toBuilder = true)
public class ApiResult {

private boolean succ = false;
private String code;
private String msg;
private Object data;

}

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
2
3
4
5
6
7
@PostMapping("/todo")
public String addTodo(@RequestBody Todo todo) {

todoBiz.addTodo(todo );

return "ok";
}

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@PostMapping("/todo")
public ApiResult addTodo(@RequestBody Todo todo) {

ApiResult.ApiResultBuilder builder = ApiResult.builder().succ(false).build().toBuilder();

try {
todoBiz.addTodo(todo);

builder.succ(true);
} catch(BizException e) {
builder.msg(e.getMessage());
}

return builder.build();
}

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
2
3
4
5
6
7
8
9
10
11
12
13
14
ApiResult.ApiResultBuilder builder = ApiResult.builder().succ(false).build().toBuilder();

try {

/**
* Implement the business logic and throw a BizException if something goes wrong
*/

builder.succ(true);
} catch(BizException e) {
builder.msg(e.getMessage());
}

return builder.build();

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
2
3
4
5
6
{
"succ": true,
"code": null,
"msg": null,
"data": null
}

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
2
3
4
5
6
7
8
9
@GetMapping("/todo")
public List<Todo> getTodoList() {

List<Todo> todos = new ArrayList<>();
todos.add(new Todo(1, "Call Metting", ""));
todos.add(new Todo(2, "Print File", ""));

return todos;
}

Now, instead, we’re going to get the to-dos in the database and transform that approach with API process templates.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@GetMapping("/todo")
public ApiResult getTodoList() {

ApiResult.ApiResultBuilder builder = ApiResult.builder().succ(false).build().toBuilder();

try {
List<Todo> list = todoBiz.listAll();
builder.data(list).succ(true);
} catch (BizException e) {
builder.msg(e.getMessage());
}

return builder.build();
}

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.

本文标题:How to build Rest Service with Spring Boot - A Step by Step Tutorial for Beginner - 3

文章作者:Morning Star

发布时间:2022年01月18日 - 12:01

最后更新:2022年01月21日 - 09:01

原始链接:https://www.mls-tech.info/java/springboot-rest-api-tutorial-3-en/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。