Java – How to add a custom property in the ResponseEntity of the Spring Boot Rest api response

How to add a custom property in the ResponseEntity of the Spring Boot Rest api response… here is a solution to the problem.

How to add a custom property in the ResponseEntity of the Spring Boot Rest api response

Since spring boot provides a ResponseEntity to represent the HTTP response of the REST API, including header, body, and status.

My RestController contains getTodoById methods like this

@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 when the API hits (api/v1/todo/13).

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

All APIs in your application need to have a common custom response structure, as shown 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 use ResponseEntity to get the required JSON response structure?

I explored it but couldn’t find a solution to the above problem.

Any help would be appreciated.
Thanks

Solution

Well, instead of returning

ResponseEntity.ok(todoItem);

You obviously need to return something similar

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
}

Related Problems and Solutions