Sub topic 5
Reading and mapping responses
This chapter assumes you can build a RestClient with a base URL, as covered earlier, and that Jackson is on the classpath. spring-boot-starter-web includes it. You should also know how JSON maps to Java records.
From retrieve() to a Java object
Every request starts with get(), post() and so on, and uri(...) sets the target. Calling retrieve() selects the retrieve path. It does not send anything yet. The request is sent when you call a terminal method that reads the response.
body(): just the data
body(Class) sends the request, picks an HttpMessageConverter based on the response Content-Type, and returns the converted object.
import org.springframework.web.client.RestClient;
record Todo(long id, String title, boolean completed) {}
class TodoReader {
private final RestClient restClient;
TodoReader(RestClient todoRestClient) {
this.restClient = todoRestClient;
}
Todo findById(long id) {
return restClient.get()
.uri("/todos/{id}", id)
.retrieve()
.body(Todo.class);
}
}Jackson matches JSON property names to record components. It ignores properties that the record does not declare, so adding a field on the server does not break your client.
body() returns null when the response has no body, for example on 204 No Content. Check for null if the API can return an empty body.
Generic types
Java erases generic type arguments at runtime. body(List.class) would give Jackson no element type, so it would build a list of maps instead of Todo objects. Pass a ParameterizedTypeReference to keep the element type:
import java.util.List;
import org.springframework.core.ParameterizedTypeReference;
List<Todo> findAll() {
return restClient.get()
.uri("/todos")
.retrieve()
.body(new ParameterizedTypeReference<List<Todo>>() {});
}The empty braces create an anonymous subclass. Its generic superclass keeps List<Todo> available at runtime. Use the same pattern for Map<String, Todo> or a wrapper such as Page<Todo>.
toEntity(): body plus status and headers
Use toEntity() when you need more than the body, such as a Location header, an ETag, or the exact status code. It returns a ResponseEntity<T>.
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
String describe(long id) {
ResponseEntity<Todo> response = restClient.get()
.uri("/todos/{id}", id)
.retrieve()
.toEntity(Todo.class);
HttpHeaders headers = response.getHeaders();
return response.getStatusCode() + " etag=" + headers.getETag()
+ " title=" + response.getBody().title();
}toEntity() also accepts a ParameterizedTypeReference, so toEntity(new ParameterizedTypeReference<List<Todo>>() {}) gives you a ResponseEntity<List<Todo>>. When you do not care about the body at all, toBodilessEntity() returns only the status and headers and discards the content.
| Method | Returns | Use when |
|---|---|---|
| `body(Class)` | `T` | You only need the data |
| `body(ParameterizedTypeReference)` | `T` (generic) | The data is a `List`, `Map` or wrapper |
| `toEntity(...)` | `ResponseEntity<T>` | You need headers or the status as well |
| `toBodilessEntity()` | `ResponseEntity<Void>` | The body is irrelevant |
Common errors
- Unexpected content type. If the server answers with
text/html, for example a login page or a proxy error, Jackson is not selected. You get aRestClientExceptionthat says no suitableHttpMessageConverterwas found. Print the response as aStringto see what the server actually sent:body(String.class). - Raw generic class. Using
body(List.class)compiles, but each element is aLinkedHashMap. You see aClassCastExceptiononly later, when you read an element as aTodo. - Unboxed
null. Callingresponse.getBody().title()without a check fails with aNullPointerExceptionwhen the body is empty. - Error statuses. A
4xxor5xxresponse does not reach your mapping.retrieve()throws an exception first. The next chapters cover how to handle that.
Exercise
An API returns a JSON array of todos and sets an ETag header. Which call gives you both the List<Todo> and the header, and why is Todo.class not enough as the type argument?
Show answer
Use toEntity(new ParameterizedTypeReference<List<Todo>>() {}). It returns a ResponseEntity<List<Todo>>, so getBody() holds the list and getHeaders().getETag() holds the header. Todo.class describes one object, not a list, and a raw List.class would lose the element type through erasure, so Jackson would produce maps.