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.
In the box
The box needs the WOD of the day from an external service, and the first version opened HTTP connections by hand. Learn RestTemplate, which is what the exam asks about, and RestClient, its fluent successor, how they handle HTTP errors and how to test them without a network using MockRestServiceServer.
AthleteWodControllerUrlConnectionWodClientWhiteboard API

WodController calls todayAsJson() on UrlConnectionWodClient, highlighted in red, which opens the connection to the Whiteboard API, outside the context.

LegacyWodClient, with RestTemplate, sends GET /wods/today to the Whiteboard API and the converter, highlighted, turns the JSON into a Wod.

LegacyWodClient, highlighted, sends POST, PUT and DELETE to the Whiteboard API.

The status handlers, highlighted, receive a 404 and turn it into an exception.

WodController calls today() on WodClient, with RestClient and highlighted, which sends get().retrieve() to the Whiteboard API.

WodClient sends onStatus(404) to the status handlers, both highlighted, to throw its own exception.

The context, WodClient and the converters, highlighted: the builder arrives already configured by Spring Boot.

In the test context, MockRestServiceServer, highlighted, takes the Whiteboard API's place and answers WodClient's expected request.

Final view: WodController and WodClient in the context, the Whiteboard API outside, and below them the converters and the status handlers.

Step 1 of 9

HTTP by hand

The box shows the WOD of the day on its screen, and it comes from an external service, the whiteboard. The first version uses HttpURLConnection:

  • it opens the connection and sets the method and headers by hand,
  • it checks the status code by hand,
  • it reads the stream… and ends up with a JSON String that still has to be converted.

Step 2 of 9

RestTemplate: reading

RestTemplate is Spring's classic HTTP client (and the one on the exam). It applies the template pattern: connection, converters and errors are its job; you ask for the resource.

  • getForObject("/wods/today", Wod.class): does a GET and turns the JSON into a Wod with Jackson's HttpMessageConverter.
  • getForEntity(...): the same but with a ResponseEntity<Wod> (status, headers and body).
  • Template variables: getForObject("/wods/{name}", Wod.class, name).

The client is built with the RestTemplateBuilder Spring Boot provides, already configured with the converters; rootUri(...) sets the base URL.

Step 3 of 9

RestTemplate: writing and exchange

For the other verbs:

  • postForObject (response body), postForEntity (everything) and postForLocation (just the Location header).
  • put(url, body, vars) and delete(url, vars), which return void.
  • exchange(url, method, HttpEntity, type): the general method, with custom headers and any verb.

For generic types like List<Wod> you need ParameterizedTypeReference: List.class loses the element type because of Java's type erasure.

Step 4 of 9

HTTP errors as exceptions

By default, RestTemplate's ResponseErrorHandler turns error statuses into exceptions:

  • 4xx → HttpClientErrorException (with subclasses: NotFound, BadRequest, Unauthorized…).
  • 5xx → HttpServerErrorException.
  • Both extend RestClientResponseException, which gives access to the status and the body.

The test answers 404 and 500 with MockRestServiceServer and checks both exceptions.

Step 5 of 9

RestClient: the fluent API

Since Spring 6.1, RestClient is RestTemplate's synchronous successor, with a fluent API:

rest.get().uri("/wods/today").accept(JSON).retrieve().body(Wod.class)

  • retrieve() sends the request; then you choose what you want: body(T), toEntity(T) (with status and headers) or toBodilessEntity().
  • post().contentType(JSON).body(wod) turns the object into JSON.
  • Same converters, same errors (RestClientResponseException) and ParameterizedTypeReference for generics.

Step 6 of 9

onStatus: your own exceptions

With RestClient you can decide what to do with each status without touching the global handler:

.retrieve().onStatus(status -> status.isSameCodeAs(NOT_FOUND), (req, res) -> { throw new WodNotFoundException(name); })

That way the rest of the application sees a domain exception (WodNotFoundException) instead of a generic HTTP exception.

Step 7 of 9

Spring Boot's builders

Look at the constructors: the clients don't call new RestTemplate() or RestClient.create(); they receive a builder from Spring Boot:

  • RestClient.Builder and RestTemplateBuilder come already configured with the HttpMessageConverters (Jackson…) and with whatever the application's RestClientCustomizer/RestTemplateCustomizer beans add (timeouts, headers, metrics).
  • The RestClient.Builder is a prototype-scoped bean: each client gets a copy and can change its baseUrl without affecting the others.

Step 8 of 9

Testing without a network: MockRestServiceServer

@RestClientTest(WodClient.class) is a test slice that starts only the client, Jackson and the builders, and sets up a MockRestServiceServer that intercepts the requests:

  1. server.expect(requestTo(...)) declares the expected request (and, with andExpect(method(POST)), content().json(...)…, how).
  2. .andRespond(withSuccess(json, APPLICATION_JSON)) prepares the response (also withCreatedEntity, withResourceNotFound, withServerError…).
  3. server.verify() checks every expected request was made.

Step 9 of 9

Recap

  • RestTemplate: getForObject/getForEntity, postForObject/postForEntity/postForLocation, put, delete, exchange.
  • RestClient: get().uri().retrieve().body(), onStatus for custom errors.
  • Errors: 4xx → HttpClientErrorException, 5xx → HttpServerErrorException.
  • Generics: ParameterizedTypeReference.
  • Spring Boot's builders, never new; @RestClientTest + MockRestServiceServer to test.

Cheatsheet →

Code

UrlConnectionWodClient.java

/** Before: plain HttpURLConnection. Connection, status, stream and JSON, all by hand. */
public class UrlConnectionWodClient {
    private final String baseUrl;

    public UrlConnectionWodClient(String baseUrl) {
        this.baseUrl = baseUrl;
    }

    public String todayAsJson() throws IOException {
        HttpURLConnection con = (HttpURLConnection) URI.create(baseUrl + "/wods/today").toURL().openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("Accept", "application/json");
        if (con.getResponseCode() != 200) {                                   // status by hand
            throw new IOException("whiteboard answered " + con.getResponseCode());
        }
        try (InputStream in = con.getInputStream()) {
            return new String(in.readAllBytes(), StandardCharsets.UTF_8);     // …and the JSON is still a String
        } finally {
            con.disconnect();
        }
    }
}

LegacyWodClient.java

public Wod today() {
    return rest.getForObject("/wods/today", Wod.class);       // just the body, JSON → Wod
}

public ResponseEntity<Wod> todayWithHeaders() {
    return rest.getForEntity("/wods/today", Wod.class);       // status + headers + body
}

public Wod byName(String name) {
    return rest.getForObject("/wods/{name}", Wod.class, name); // URI template variables
}

LegacyWodClient.java

public URI publish(Wod wod) {
    return rest.postForLocation("/wods", wod);                // POST, returns the Location header
}

public void rename(String name, Wod wod) {
    rest.put("/wods/{name}", wod, name);                      // PUT, returns nothing
}

public void remove(String name) {
    rest.delete("/wods/{name}", name);
}

public List<Wod> history() {
    return rest.exchange("/wods", HttpMethod.GET, null,       // the general-purpose method
        new ParameterizedTypeReference<List<Wod>>() { }).getBody(); // generic type survives erasure
}

LegacyWodClientTest.java

@Test
void errorStatusesBecomeExceptions() {
    server.expect(requestTo("/wods/Nope")).andRespond(withResourceNotFound());
    server.expect(requestTo("/wods/Boom")).andRespond(withServerError());

    assertThatThrownBy(() -> client.byName("Nope"))
        .isInstanceOf(HttpClientErrorException.NotFound.class);    // 4xx → HttpClientErrorException
    assertThatThrownBy(() -> client.byName("Boom"))
        .isInstanceOf(HttpServerErrorException.class);             // 5xx → HttpServerErrorException
}

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

WodClient.java

public Wod byName(String name) {
    return rest.get().uri("/wods/{name}", name)
        .retrieve()
        .onStatus(status -> status.isSameCodeAs(HttpStatus.NOT_FOUND),   // map a status to YOUR exception
            (request, response) -> { throw new WodNotFoundException(name); })
        .body(Wod.class);
}

WodClient.java

public WodClient(RestClient.Builder builder, @Value("${whiteboard.url}") String baseUrl) {
    this.rest = builder.baseUrl(baseUrl).build();  // prototype builder from Boot, with message converters
}

WodClientTest.java

@RestClientTest(WodClient.class)            // slice: the client, Jackson and a MockRestServiceServer
@TestPropertySource(properties = "whiteboard.url=http://whiteboard")
class WodClientTest {
    @Autowired WodClient client;
    @Autowired MockRestServiceServer server; // answers instead of the real whiteboard

    @Test
    void readsTheWodOfTheDay() {
        server.expect(requestTo("http://whiteboard/wods/today"))
            .andRespond(withSuccess("""
                {"name": "Fran", "type": "for time", "minutes": 10}""", MediaType.APPLICATION_JSON));

        assertThat(client.today()).isEqualTo(new Wod("Fran", "for time", 10));
        server.verify();                     // every expected request was made
    }
    // …
}

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

Quiz

1. Which RestTemplate method gives you the status code and headers besides the body?

2. rest.getForObject("/wods/{name}", Wod.class, "Nope") gets a 404. What happens?

3. You want to receive a List<Wod>. What do you use with RestTemplate?

4. What does postForLocation return?

5. Which statement about RestClient is correct?

6. What does @RestClientTest(WodClient.class) do?

Cheatsheet → · Mock exam →

Run it