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)
sequenceDiagram
actor C as API client
participant D as DispatcherServlet
participant J as Jackson converter
participant V as Bean Validation
participant B as BookingController
participant A as ApiErrors «@RestControllerAdvice»
C->>D: POST /api/bookings (Content-Type: application/json)
D->>J: read body → BookingRequest
D->>V: @Valid
alt invalid
V-->>D: MethodArgumentNotValidException
D->>A: @ExceptionHandler
A-->>C: 400 ProblemDetail
else valid
D->>B: create(request)
B-->>D: ResponseEntity.created(location).body(booking)
D->>J: write Booking → JSON
D-->>C: 201 Created + Location
endKey pieces
@RestController,@RequestMapping(produces, consumes),@GetMapping/@PostMapping/@PutMapping/@PatchMapping/@DeleteMapping@RequestBody+HttpMessageConverter(Jackson): JSON ↔ objectsResponseEntity<T>: status, headers and body (created(uri),ok(),noContent(),notFound())@ResponseStatuson 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 (+
Locationheader), 204 No Content, 400, 401, 403, 404, 405, 406, 409, 415, 500 @RequestBodyrequires a body; with@Valid, validation errors give 400producesis matched againstAccept(no match → 406);consumes, againstContent-Type(no match → 415)- An
@ExceptionHandlerinside a controller only covers that controller; in a@RestControllerAdvice, all of them ServletUriComponentsBuilder.fromCurrentRequest()builds the URI forLocation
Exam traps
- Without
@Valid(or@Validated), the DTO's validation annotations are not checked - A
voidmethod without@ResponseStatusanswers 200, not 204 @ResponseStatuson an exception only applies if no@ExceptionHandlerhandles it first- PUT should send the whole resource; for partial changes, PATCH