@ResponseStatus declares the HTTP status returned by a controller method. Use it when the default 200 (OK) does not describe the result accurately. section 7.1.2
Choose a status that communicates what the operation accomplished:
- Return 201 (CREATED) after a POST request successfully creates a resource. section 7.1.2
- Return 204 (NO_CONTENT) after a DELETE operation, because the deleted resource supplies no response body. section 7.1.4
- Use a different response approach when deletion should report a missing resource, such as returning ResponseEntity with NOT_FOUND. section 7.1.4
@PostMapping(consumes="application/json")
@ResponseStatus(HttpStatus.CREATED)
public Taco postTaco(@RequestBody Taco taco) {
return tacoRepo.save(taco);
}
A POST endpoint combines @ResponseStatus(HttpStatus.CREATED) with @RequestBody and repository persistence. section 7.1.2
@DeleteMapping("/{orderId}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteOrder(@PathVariable("orderId") Long orderId) {
try {
repo.deleteById(orderId);
} catch (EmptyResultDataAccessException e) {}
}
A DELETE endpoint returns 204 and suppresses EmptyResultDataAccessException when the requested resource is already absent. section 7.1.4
