Video in progress
Why do we need ResponseEntity?
With ResponseEntity you fully control the response: besides the body, you also set the HTTP status and headers.
📖 Answer
If you return a plain object, the status is always 200. Often you need a different code:
@GetMapping("/api/products/{id}")
public ResponseEntity<ProductDto> get(@PathVariable long id) {
return products.find(id)
.map(ResponseEntity::ok) // 200
.orElse(ResponseEntity.notFound().build()); // 404
}
@PostMapping("/api/products")
public ResponseEntity<ProductDto> create(@RequestBody NewProduct p) {
ProductDto saved = products.create(p);
return ResponseEntity
.created(URI.create("/api/products/" + saved.id())) // 201 + Location
.body(saved);
}
If the status is always 200, returning the object itself is enough. For errors, don't build a ResponseEntity in every method: throw an exception and turn it into a response in one place in @RestControllerAdvice — it comes out much cleaner.
Sign up to mark studied questions and save your progress.