liveBook · Manning

ResponseEntity

As explained in Spring Start Here, Second Edition

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

ResponseEntity represents an HTTP response with a body, status, and headers. Return it from a Spring endpoint when the default response needs customization. section 10.3.2

Build the response by choosing what the endpoint should send:

  • Set a status with status(HttpStatus.ACCEPTED), add headers with header(...), and provide the body with body(...). section 10.3.2
  • Return different response bodies and statuses for success and failure. Exception handling can live in the endpoint or in a REST controller advice. section 10.3.3
Listing 10.9 Adding custom headers and setting a response status
@RestController
public class CountryController {
 
  @GetMapping("/france")
  public ResponseEntity<Country> france() {
    Country c = Country.of("France", 67);
    return ResponseEntity
            .status(HttpStatus.ACCEPTED)  #A
            .header("continent", "Europe")                   #B
            .header("capital", "Paris")                      #B
            .header("favorite_food", "cheese and wine")      #B
            .body(c);    #C
  }
}

A country endpoint returns France with status 202 Accepted and three custom headers. section 10.3.2

Payment failure

A payment endpoint can return an ErrorDetails body with 400 Bad Request when insufficient funds trigger an exception. section 10.3.3

How Spring Start Here, Second Edition covers it

How deep it goes
Demonstrates response construction and endpoint-level exception handling, then contrasts handling exceptions in controller advice.
Examples
Uses a France endpoint with custom headers and a payment endpoint returning an error response.
What you can do after
Apply it via Spring to return endpoint responses with chosen bodies, statuses, and headers.
How it connects
Connects HTTP responses with REST endpoints, Spring MVC, and exception handling.

Also explained in

Compare how 2 books explain ResponseEntity →

Related concepts

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