liveBook · Manning

ResponseEntity

As explained in Spring in Action, Sixth Edition

ResponseEntity is a Spring type that represents an HTTP response together with its body, headers, and other response details.

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

How Spring in Action, Sixth Edition covers it

How deep it goes
Explains server-side construction and client-side inspection with worked code, but stops short of broader response customization.
Examples
Uses Taco lookup, missing-resource handling, ingredient retrieval, and Date-header logging as concrete examples.
What it assumes
Assumes basic REST controller and repository usage while demonstrating Optional lookup and direct response writing.
What you can do after
Apply it via Spring MVC and getForEntity to return resources with statuses or inspect headers around a payload.
How it connects
Connects REST controllers with HTTP response bodies, headers, status codes, and Spring MVC resource retrieval.

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.