liveBook · Manning

@responsestatus

As explained in Spring in Action, Sixth Edition

@ResponseStatus is a Spring annotation that declares the HTTP status code returned by a controller method or exception handler.

@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

How Spring in Action, Sixth Edition covers it

How deep it goes
Explains status selection through POST and DELETE examples but does not detail annotation internals or exception-handler usage.
Examples
Uses Taco creation with 201 CREATED and order deletion with 204 NO_CONTENT as concrete controller examples.
What you can do after
Apply via Spring MVC by annotating controller methods with the HTTP status that best describes each operation.
How it connects
Connects HTTP status codes with REST APIs, POST requests, DELETE requests, ResponseEntity, and repository operations.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring in Action, Sixth Edition. The section links point to the parts of the book it draws on.