Card 03/ 06

ExampleDifficulty: Intermediate1 min

The ResponseEntity That Matches What Happened

Three calls against the controller from the previous card, and three different outcomes — each one because the handler reached for the ResponseEntity factory method that actually describes what it did.

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);
}
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() sets the Location header pointing at the new resource, which ok() never does — returning ResponseEntity.ok(ride) from createRide would give a client a 200 with no way to know where the new ride actually lives.