Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return ResponseEntity vs returning POJO

Tags:

My application is based on Spring Boot with some REST endpoints. Is there any difference between below return statements?

  • return new ResponseEntity<MyBean>(myBean, HttpStatus.OK)

  • return myBean;

Is there any best practice guidelines or any technical difference?

like image 916
Abhishek Chatterjee Avatar asked Apr 05 '18 13:04

Abhishek Chatterjee


People also ask

What is the return type of ResponseEntity?

A ResponseEntity is returned. We give ResponseEntity a custom status code, headers, and a body. With @ResponseBody , only the body is returned. The headers and status code are provided by Spring.

Should we use ResponseEntity?

ResponseEntity represents the whole HTTP response: status code, headers, and body. As a result, we can use it to fully configure the HTTP response. If we want to use it, we have to return it from the endpoint; Spring takes care of the rest.

Should a service return ResponseEntity?

Yes, Service returning domain object should be preferable to a Service returning ResponseEntity<> . There is no best practices. Having said that, you should think of implementing something like Hexagonal or Layered architecture.


1 Answers

ResponseEntity<T> represents the entire HTTP response. Besides the body, its API allows you to set headers and a status code to the response.

Returning just a bean is fine but doesn't give you much flexibility: In the future, if you need to add a header to the response or modify the status code, for example, you need to change the method return type.

For more details on return values, refer to the Spring MVC documentation.

like image 54
cassiomolin Avatar answered Sep 21 '22 08:09

cassiomolin