Cheatsheet

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`.

Diagram (UML)

ApplicationContextAPI clientDispatcherServletBookingControllerBookingStoreJackson converterBean ValidationApiErrors (advice)

Key pieces

  • @RestController, @RequestMapping(produces, consumes), @GetMapping/@PostMapping/@PutMapping/@PatchMapping/@DeleteMapping
  • @RequestBody + HttpMessageConverter (Jackson): JSON ↔ objects
  • ResponseEntity<T>: status, headers and body (created(uri), ok(), noContent(), notFound())
  • @ResponseStatus on a method or on an exception class
  • @Valid + Bean Validation (@NotBlank, @Size…) → MethodArgumentNotValidException
  • @ExceptionHandler, @RestControllerAdvice, ProblemDetail (RFC 9457)

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"));
}

Remember for the exam

  • Verbs: GET reads (safe and idempotent), POST creates (neither safe nor idempotent), PUT replaces (idempotent), PATCH partially modifies, DELETE removes (idempotent)
  • Codes: 200 OK, 201 Created (+ Location header), 204 No Content, 400, 401, 403, 404, 405, 406, 409, 415, 500
  • @RequestBody requires a body; with @Valid, validation errors give 400
  • produces is matched against Accept (no match → 406); consumes, against Content-Type (no match → 415)
  • An @ExceptionHandler inside a controller only covers that controller; in a @RestControllerAdvice, all of them
  • ServletUriComponentsBuilder.fromCurrentRequest() builds the URI for Location

Exam traps

  • Without @Valid (or @Validated), the DTO's validation annotations are not checked
  • A void method without @ResponseStatus answers 200, not 204
  • @ResponseStatus on an exception only applies if no @ExceptionHandler handles it first
  • PUT should send the whole resource; for partial changes, PATCH

← REST controllers · Run it