Skip to content
Advertisement

What’s the difference between return type of ResponseEntity and simple object (ex. User) in REST Spring Java?

I’m new to REST and I’m making simple REST application with users and articles. I wonder what’s the difference between two samples below:

@GetMapping("/user/{id}")
public User getUserById(PathVariable("id") String id) {
 .....
 return userService.getUserById();
}

and

@GetMapping("/user/{id}")
public ResponseEntity<User> getUserById(PathVariable("id") String id) {
 .....
  return new ResponseEntity<> ....
}

Which one is better to use? And what’s the main difference between two of them?

Advertisement

Answer

ResponseEntity is containing the entire HTTP response that returns as a response which gives the flexibility to add headers, change status code and do similar things to the response.

Another hand sending PJO class directly like returning users in the example is somewhat similar to return ResponseEntity.ok(user) which responded to user details successfully to the user. But the ability to change headers, status codes is not available if you return PJO directly.

It is good to use ResponseEntity over PJO when there is a scenario you need to change the headers or you need to change status according to the result.

eg: show not found when there is no data you can return ResponseEntity.status(404).body(<-body->).

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement