REST controllers
- Key idea
- A REST API exposes resources at URLs and uses HTTP verbs and status codes with their meaning. In Spring, a `@RestController` receives the body with `@RequestBody` (converted by an `HttpMessageConverter`), returns objects or a `ResponseEntity` and leaves errors to `@ExceptionHandler` and `@RestControllerAdvice`.
- In the box
- The old booking API answered 200 to everything and hid the errors in the body. Rebuild it as REST with @RestController, @RequestBody, ResponseEntity and the right status codes, validate the input and centralise errors in a @RestControllerAdvice.
The client sends GET /getBooking/2 and NaiveBookingController, highlighted in red, returns a 200 that says not found.
The client sends GET /api/bookings/1; the DispatcherServlet calls one(1) on BookingController, highlighted.
A POST with JSON reaches the DispatcherServlet, which passes the body to the Jackson converter, highlighted, to turn it into a record.
BookingController stores the booking with add() in BookingStore, both highlighted, and the 201 response with Location goes back to the client.
BookingController, highlighted, returns 204 when cancelling and 409 when the class is full.
The DispatcherServlet asks Bean Validation, highlighted, to validate the body; @Valid fails and the request never reaches the controller.
A BookingNotFoundException travels from the DispatcherServlet to ApiErrors, the highlighted advice, which turns it into a 404 with ProblemDetail.
The DispatcherServlet and the converter, highlighted, return 415, 406 or 405 to the client when the request doesn't fit what's declared.
Final view: the client, the DispatcherServlet, BookingController and BookingStore on top; the converter, validation and the advice below.
Step 1 of 9
Everything is a 200
The old API (NaiveBookingController) has two bad habits:
- Verbs in the URL:
/legacy/getBooking/2,/legacy/cancelBooking/2… - Always 200: if the booking doesn't exist it answers
200 OKwith{"ok": false, "error": "not found"}.
An HTTP client, a cache or a gateway sees a 200 and thinks everything went fine. Each client has to read the body to know whether there was an error.
Step 2 of 9
Resources and verbs with @RestController
In REST, URLs name resources and HTTP verbs say what to do with them:
| Request | Meaning |
|---|---|
GET /api/bookings |
the collection |
GET /api/bookings/1 |
one booking |
POST /api/bookings |
create one |
PUT /api/bookings/1 |
replace it entirely |
DELETE /api/bookings/1 |
delete it |
BookingController is a @RestController (@Controller + @ResponseBody). @RequestMapping(path = "/api/bookings", produces = "application/json") sets the prefix and that every response is JSON.
Step 3 of 9
@RequestBody: JSON to object
To create, the client sends the JSON in the body. @RequestBody BookingRequest request asks the DispatcherServlet to convert it:
- An
HttpMessageConverteris chosen from theContent-Type. Withapplication/json, Jackson turns the JSON into theBookingRequestrecord. consumes = "application/json"restricts what the method accepts.@Validalso asks for the DTO's constraints to be validated (you'll see it in the validation step).
Step 4 of 9
ResponseEntity: 201 and Location
When creating, the right response is 201 Created with a Location header pointing to the new resource. Returning just the object would give a 200.
ResponseEntity<T> lets you control the status, headers and body:
ResponseEntity.created(location).body(created)→ 201 +Location+ JSON.- Other forms:
ok(body),noContent().build(),notFound().build(),status(HttpStatus.ACCEPTED).header(...).body(...).
ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}") builds http://…/api/bookings/1 from the current request.
Step 5 of 9
@ResponseStatus: codes without ResponseEntity
When you don't need headers, @ResponseStatus sets the code:
- On the method:
@DeleteMapping+@ResponseStatus(NO_CONTENT)→ 204 with no body. Without the annotation, avoidmethod answers 200. - On the exception:
ClassFullExceptioncarries@ResponseStatus(CONFLICT); if it leaves a handler and nobody handles it, the response is 409.
About the verbs: PUT replaces the whole resource and is idempotent (repeating it changes nothing more). PATCH changes a part. POST isn't idempotent: repeating it creates another resource.
Step 6 of 9
@Valid and Bean Validation
BookingRequest declares rules with Bean Validation: @NotBlank and @Size(max = 80) on athlete, @NotBlank on wod.
With @Valid on the parameter, Spring checks them before calling the method. If any fails, it throws MethodArgumentNotValidException and the response is 400. The test sends an empty athlete and checks the 400 and the field detail.
Step 7 of 9
@RestControllerAdvice: errors in one place
To avoid repeating error handling in every controller:
@ExceptionHandler(BookingNotFoundException.class)turns an exception into a response. Inside a controller, it only covers that controller.- In a
@RestControllerAdviceclass (@ControllerAdvice+@ResponseBody), the handlers cover every controller. ProblemDetailis the standard error format (RFC 9457,application/problem+json):status,title,detailand any properties you add (here,fieldswith the validation errors).
Step 8 of 9
Content negotiation: 406, 415 and 405
The DispatcherServlet compares the request with what the method declares:
- The body's
Content-Typeagainstconsumes. A POST withtext/plain→ 415 Unsupported Media Type. Acceptagainstproduces(and the available converters). Asking a JSON-only API forapplication/xml→ 406 Not Acceptable.- The path exists but not for that verb (
DELETE /api/bookings) → 405 Method Not Allowed.
Step 9 of 9
Recap
- REST: resources in URLs, HTTP verbs for actions, codes for results.
@RestController+@RequestBody(Jackson) for JSON in and out.ResponseEntityfor status and headers (201 +Location);@ResponseStatusfor fixed codes (204, 409).@Valid+ Bean Validation → 400.@RestControllerAdvice+@ExceptionHandler+ProblemDetailfor uniform errors.- 415 / 406 / 405 come out of
consumes,producesand the verbs on their own.
Code
NaiveBookingController.java
/** Before: always 200, errors hidden inside the body, verbs in the URL. */
@RestController
public class NaiveBookingController {
@GetMapping("/legacy/getBooking/{id}") // a verb in the URL
public Map<String, Object> get(@PathVariable long id) {
if (id != 1) {
return Map.of("ok", false, "error", "not found"); // a 200 that is really a 404
}
return Map.of("ok", true, "athlete", "Ana");
}
}BookingController.java
@RestController // @Controller + @ResponseBody on every method
@RequestMapping(path = "/api/bookings", produces = MediaType.APPLICATION_JSON_VALUE)
public class BookingController {
private final BookingStore store;
public BookingController(BookingStore store) {
this.store = store;
}
@GetMapping("/{id}") // GET /api/bookings/7 → one resource
public Booking one(@PathVariable long id) {
return store.find(id).orElseThrow(() -> new BookingNotFoundException(id));
}
@GetMapping // GET /api/bookings → the collection
public Collection<Booking> all() {
return store.all();
}
// …
}BookingController.java
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Booking> create(@Valid @RequestBody BookingRequest request) { // JSON → record
Booking created = store.add(request.athlete(), request.wod());
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}").buildAndExpand(created.id()).toUri();
return ResponseEntity.created(location).body(created); // 201 + Location header + body
}BookingController.java
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Booking> create(@Valid @RequestBody BookingRequest request) { // JSON → record
Booking created = store.add(request.athlete(), request.wod());
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}").buildAndExpand(created.id()).toUri();
return ResponseEntity.created(location).body(created); // 201 + Location header + body
}BookingController.java
@PutMapping(path = "/{id}", consumes = MediaType.APPLICATION_JSON_VALUE)
public Booking replace(@PathVariable long id, @Valid @RequestBody BookingRequest request) {
return store.replace(id, request.athlete(), request.wod()); // idempotent: same result every time
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT) // 204, empty body
public void cancel(@PathVariable long id) {
store.remove(id);
}BookingApiTest.java
@Test
void invalidBodiesAre400WithTheFieldErrors() throws Exception {
mvc.perform(post("/api/bookings").contentType(MediaType.APPLICATION_JSON)
.content("{\"athlete\": \"\", \"wod\": \"Fran\"}"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.fields.athlete").exists());
}ApiErrors.java
@RestControllerAdvice // applies to every controller
public class ApiErrors {
@ExceptionHandler(BookingNotFoundException.class)
public ProblemDetail notFound(BookingNotFoundException e) { // RFC 9457 problem+json
return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, e.getMessage());
}
@ExceptionHandler(MethodArgumentNotValidException.class) // @Valid failed
public ProblemDetail invalid(MethodArgumentNotValidException e) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "invalid booking");
Map<String, String> fields = e.getBindingResult().getFieldErrors().stream()
.collect(Collectors.toMap(f -> f.getField(), f -> String.valueOf(f.getDefaultMessage()), (a, b) -> a));
problem.setProperty("fields", fields);
return problem;
}
}BookingApiTest.java
@Test
void contentNegotiationErrors() throws Exception {
mvc.perform(post("/api/bookings").contentType(MediaType.TEXT_PLAIN).content("Ana, Fran"))
.andExpect(status().isUnsupportedMediaType()); // 415: body type not in "consumes"
mvc.perform(get("/api/bookings").accept(MediaType.APPLICATION_XML))
.andExpect(status().isNotAcceptable()); // 406: can't produce what Accept asks
mvc.perform(delete("/api/bookings"))
.andExpect(status().isMethodNotAllowed()); // 405: path exists, verb doesn't
}BookingApiTest.java
@Test
void postCreatesAResourceWith201AndLocation() throws Exception {
mvc.perform(post("/api/bookings").contentType(MediaType.APPLICATION_JSON).content(ANA))
.andExpect(status().isCreated()) // 201
.andExpect(header().string("Location", endsWith("/api/bookings/1")))
.andExpect(jsonPath("$.athlete").value("Ana"));
mvc.perform(get("/api/bookings/1")).andExpect(status().isOk());
mvc.perform(delete("/api/bookings/1")).andExpect(status().isNoContent()); // 204
mvc.perform(get("/api/bookings/1"))
.andExpect(status().isNotFound()) // 404 from the advice
.andExpect(jsonPath("$.detail").value("no booking 1"));
}