4

I can define a GET method in two ways:

public ResponseEntity<Pet> getPetById(Long id);

and

public Pet getPetById(Long id);

They seem to be equivalent, except that the first one involves more boilerplate code. So, what is the reason to use ResponseEntity and what advantages it brings?

Phate
  • 6,066
  • 15
  • 73
  • 138
  • 3
    Does this answer your question? [When use ResponseEntity and @RestController for Spring RESTful applications](https://stackoverflow.com/questions/26549379/when-use-responseentityt-and-restcontroller-for-spring-restful-applications) – jonrsharpe Apr 10 '20 at 11:03
  • It is - the difference is that in first example you can manually set headers, response code, body etc by yourself using builder. – Antoniossss Apr 10 '20 at 11:08
  • you can see the answer here: https://stackoverflow.com/questions/26549379/when-use-responseentityt-and-restcontroller-for-spring-restful-applications – Mohamad Mirzadeh Feb 20 '23 at 11:40

2 Answers2

5

The difference is quite easy to explain. When you use ResponseEntity, you have full control about the contents of your response. You can change your headers, status code, ... When you don't use ResponseEntity as the return type of a controller method, spring will "automagically" create a default ResponseEntity.

So the biggest advantage in using ResponseEntity is that you have full control. The disadvantage is that it is more verbose than letting Spring work its magic.

1

It allows you to customize the HTTP response sent back to the client.

Advantages:

  • You can use the HttpStatus enum provided by Spring to choose from a wide range of standard HTTP status codes or create custom ones if needed.
  • You can set custom headers for the response. This is useful when you want to provide additional information to the client, such as content type, caching directives, authentication-related headers, or any other custom headers required for your application.
  • You can also return custom objects as the response body, which will be automatically serialized to the specified content type.

Disadvantages:

  • It adds some complexity to your code. You need to explicitly create and configure a ResponseEntity object for each response.
omernaci
  • 383
  • 3
  • 16