Cheatsheet

Calling REST APIs

Key idea

`RestTemplate` and `RestClient` are Spring's synchronous HTTP clients: they build the request, convert objects to and from JSON with the same `HttpMessageConverter`s as Spring MVC and turn 4xx/5xx statuses into exceptions. `RestTemplate` has one named method per operation; `RestClient` (Spring 6.1+) a fluent API.

Diagram (UML)

AthleteApplicationContextWodControllerWodClient (RestClient)Whiteboard APIHttpMessageConvertersstatus handlers

Key pieces

  • RestTemplate: getForObject, getForEntity, postForObject, postForEntity, postForLocation, put, delete, exchange, execute
  • RestClient: get()/post()/put()/delete() → .uri(...) → .retrieve() → .body(T) / .toEntity(T) / .toBodilessEntity()
  • ParameterizedTypeReference<List<Wod>>: generic types in the response
  • HttpClientErrorException (4xx), HttpServerErrorException (5xx), both RestClientResponseException
  • RestTemplateBuilder and RestClient.Builder: built by Spring Boot, already configured
  • @RestClientTest + MockRestServiceServer: test the client without a network

WodClient.java

public Wod today() {
    return rest.get()
        .uri("/wods/today")
        .accept(MediaType.APPLICATION_JSON)
        .retrieve()                                // send it and look at the response
        .body(Wod.class);                          // JSON → Wod (4xx/5xx → RestClientResponseException)
}

public List<Wod> history() {
    return rest.get().uri("/wods").retrieve()
        .body(new ParameterizedTypeReference<List<Wod>>() { });
}

public URI publish(Wod wod) {
    return rest.post().uri("/wods")
        .contentType(MediaType.APPLICATION_JSON)
        .body(wod)                                 // Wod → JSON
        .retrieve()
        .toBodilessEntity()
        .getHeaders().getLocation();
}

Remember for the exam

  • getForObject returns only the body; getForEntity, a ResponseEntity with status and headers
  • postForLocation returns the Location header (a URI)
  • exchange is the general method: verb, HttpEntity (body and headers) and response type
  • Template variables (/wods/{name}) are filled from the extra arguments or a Map
  • RestTemplate is in maintenance mode: it isn't removed, but the new options are RestClient (synchronous) or WebClient (reactive)
  • Inject Spring Boot's builder, don't call new RestTemplate(): that way you inherit converters, timeouts and customizations

Exam traps

  • With RestTemplate, a 404 throws HttpClientErrorException.NotFound; it doesn't return null
  • For List<Wod> you need ParameterizedTypeReference (or a Wod[] array); List.class loses the generic type
  • RestTemplate's put and delete return void; to read the response use exchange
  • With rootUri/baseUrl, MockRestServiceServer expectations use the relative path

← Calling REST APIs · Run it