3

As spring boot provides the ResponseEntity to represent a HTTP response for rest apis, including headers, body, and status.

My RestController contains getTodoById method like below-

@GetMapping("/todo/{id}")
 public Todo getTodoById(@PathVariable String id) {
        int todoId = Integer.parseInt(id);
        Todo todoItem = todoRepository.findById(todoId);
         ResponseEntity.ok(todoItem);
    }

It gives the following api response on api hit(api/v1/todo/13).

{
    "id": 13,
    "title": "title13",
    "status": "not started"
}

There is need to have a common customised response structure for all apis in the application as below-

{
  "status": "success",
  "data": {
    "id": 13,
    "title": "title13",
    "status": "not started"
  },
  "error": null,
  "statusCode": 200
}

{
  "status": "failure",
  "data": {},
  "error": "bad request",
  "statusCode": 400
}

How do i get the required JSON response structure using ResponseEntity?

I explored it but could not find the solution which solve the above problem.

Any help would be appreciated. Thanks

Siyaram Malav
  • 4,414
  • 2
  • 31
  • 31
  • Maybe you can get some inspiration from [Spring Boot's tracing feature](https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-features.html#production-ready-http-tracing)? – wjans Jan 23 '20 at 13:23

1 Answers1

5

Well, instead of returning

ResponseEntity.ok(todoItem);

you obviously need to return something like

ResponseEntity.ok(new Response(todoItem));

with

public class Response {

    private String status = "success";

    private Object data;

    private String error;

    private int statusCode = 200;

    // Constructor, getters and setters omitted
}
Smutje
  • 17,733
  • 4
  • 24
  • 41