ResponseEntity represents an HTTP response as a single object, combining a response body with details such as headers and status. On the server, a controller can return it to write data directly into the response instead of passing data through a model and view. section 7.1.1 section 7.3.1
Use ResponseEntity when the endpoint or client needs more control than a plain body object provides:
- Return a successful resource with an explicit HTTP status, such as OK. section 7.1.1
- Return a missing resource with NOT_FOUND instead of treating every lookup result as successful. section 7.1.1
- Inspect response metadata such as the Date header while retrieving a resource. section 7.3.1
Returning a taco or a 404 response
A REST controller looks up a taco by ID, wraps a found Taco in ResponseEntity with HttpStatus.OK, and returns an empty body with HttpStatus.NOT_FOUND when no taco exists. section 7.1.1
@GetMapping("/{id}")
public ResponseEntity<Taco> tacoById(@PathVariable("id") Long id) {
Optional<Taco> optTaco = tacoRepo.findById(id);
if (optTaco.isPresent()) {
return new ResponseEntity<>(optTaco.get(), HttpStatus.OK);
}
return new ResponseEntity<>(null, HttpStatus.NOT_FOUND);
}
View the complete handler pattern for choosing between a successful Taco response and a NOT_FOUND response. section 7.1.1
