Card 03/ 06

ExampleDifficulty: Intermediate1 min

ResponseEntity Example: Choosing the Response That Matches the Outcome

404 for a missing ride, 201 with a Location header for a new one, and 200 for one that was found.

ResponseEntity is the object a controller method returns to control the whole HTTP response: the status code, the headers and the body. Its factory methods, such as ok(), created() and notFound(), each describe one outcome, and choosing the one that matches what happened gives the client the right status and headers.

Two handlers in a controller for rides, each returning a different ResponseEntity depending on the outcome:

java
ResponseEntity<Ride> getRide(@PathVariable String id) {
    Ride ride = rides.get(id);
    if (ride == null) {
        return ResponseEntity.notFound().build();
    }
    return ResponseEntity.ok(ride);
}

ResponseEntity<Ride> createRide(@RequestBody Ride ride) {
    rides.put(ride.id(), ride);
    return ResponseEntity.created(URI.create("/rides/" + ride.id())).body(ride);
}

Three real HTTP calls against these handlers:

text
GET /rides/nope     -> 404
POST /rides          -> 201, Location: /rides/ride-1
GET /rides/ride-1    -> 200, body: {"id":"ride-1","pickup":"Main St"}
run in a container against a real embedded server, real HTTP calls

created() answers 201 Created and sets the Location header to the new ride's address, which ok() never does. Returning ResponseEntity.ok(ride) from createRide would give the client a 200 and no way to know where the new ride lives.

So choose the factory method by what happened, not by what you want to send back: clients, proxies and monitoring tools all read the status code before anything else.