An HTTP response code is a three-digit status code that tells a client what happened when the server processed a request. In a REST API, the code should describe the outcome accurately: a response with a null body and 200 (OK) can mislead a client when the requested resource does not exist. section 7.1.1
Choose a code that matches the result:
- 200 (OK): a requested taco was found and returned. section 7.1.1
- 404 (NOT FOUND): the requested taco does not exist. section 7.1.1
- 201 (CREATED): a POST request saved a new taco. section 7.1.2
- 204 (NO CONTENT): an order was deleted and no response body is needed. section 7.1.4
A Spring MVC controller can return a ResponseEntity when the status depends on what happens inside the method. For a lookup, check the repository result: return the taco with HttpStatus.OK if present, or a null body with HttpStatus.NOT_FOUND if absent. 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);
}
The GET handler checks the Optional returned by findById() before choosing between 200 and 404. section 7.1.1
When a handler has one intended success status, @ResponseStatus sets it directly. A POST handler uses HttpStatus.CREATED to say that it created a resource, rather than relying on the usual 200. A DELETE handler uses HttpStatus.NO_CONTENT to tell the client not to expect response data. section 7.1.2 section 7.1.4
@PostMapping(consumes="application/json")
@ResponseStatus(HttpStatus.CREATED)
public Taco postTaco(@RequestBody Taco taco) {
return tacoRepo.save(taco);
}
The POST handler saves a taco and marks its successful response as 201 (CREATED). section 7.1.2
@DeleteMapping("/{orderId}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteOrder(@PathVariable("orderId") Long orderId) {
try {
repo.deleteById(orderId);
} catch (EmptyResultDataAccessException e) {}
}
The DELETE handler returns no body and marks its response as 204 (NO CONTENT). It also chooses to ignore a missing order rather than return 404. section 7.1.4










