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

1

1 Answer 1

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.