Sub topic 5
Reading and mapping responses
This chapter assumes you can write a Spring Boot @Configuration class and inject beans. It also assumes you know Java records and can read a JSON document. You should already have a RestClient built with a base URL, as in the previous chapters. Here you will turn the HTTP response into Java objects.
The retrieve() step
Every RestClient call follows the same shape: pick a method, set the URI, then say how to get the result. For most calls the last step starts with retrieve().
retrieve() sends the request and returns a ResponseSpec. This object lets you choose what to read from the response. It does not return data by itself. The main choices are:
| Method | Returns | Use it when |
|---|---|---|
| `body(Class<T>)` | `T` | You only need the body as a simple type. |
| `body(ParameterizedTypeReference<T>)` | `T` | The body is a generic type such as `List<Todo>`. |
| `toEntity(Class<T>)` | `ResponseEntity<T>` | You need the status or headers as well as the body. |
| `toEntity(ParameterizedTypeReference<T>)` | `ResponseEntity<T>` | You need both, and the body is generic. |
| `toBodilessEntity()` | `ResponseEntity<Void>` | You need only the status and headers. |
The request is sent when you call one of these final methods. Before that, you can still add status handlers with onStatus, which the error handling chapter covers.
Mapping a body to a type
The simplest case is body(Class). Spring reads the Content-Type header of the response, picks a matching HttpMessageConverter, and builds an object of the type you asked for. For application/json the converter is Jackson. With a Spring Boot RestClient.Builder, it uses the same ObjectMapper configuration as the rest of your application.
import org.springframework.web.client.RestClient;
record Todo(long id, String title, boolean completed) {}
class TodoReader {
private final RestClient restClient;
TodoReader(RestClient restClient) {
this.restClient = restClient;
}
Todo findById(long id) {
return restClient.get()
.uri("/todos/{id}", id)
.retrieve()
.body(Todo.class);
}
}Jackson matches JSON property names to record component names. A response such as {"id":1,"title":"Write docs","completed":false} becomes new Todo(1, "Write docs", false).
Some details that cause trouble in practice:
- Unknown properties. If the JSON has fields your record does not declare, Spring's default Jackson setup ignores them. This is useful because a server can add fields without breaking your client.
- Missing properties. A missing JSON field becomes
nullfor object types and0orfalsefor primitives. A record withlong idwill silently get0if the server omitsid. UseLongif you need to detect the absence. - Different names. If the JSON uses
user_idand your component isuserId, add@JsonProperty("user_id")to the component.
Reading the body as text or bytes
body(String.class) returns the raw text of the response. This is the quickest way to see what a server really sent when a mapping fails. body(byte[].class) returns the bytes, which suits downloads of small files.
String raw = restClient.get()
.uri("/todos/{id}", 1)
.retrieve()
.body(String.class);Both read the full body into memory. For a very large download, retrieve() is not the right tool. Use exchange(), covered in a later chapter, so you can stream.
Reading into a JSON tree
If you do not want to define a type, you can ask for Jackson's tree model, JsonNode. This is handy for a quick look at a response or for an API whose shape varies.
import com.fasterxml.jackson.databind.JsonNode;
String title = restClient.get()
.uri("/todos/{id}", 1)
.retrieve()
.body(JsonNode.class)
.path("title")
.asText();Prefer a record when the shape is stable. A record gives you compile-time names and fails early when the structure is wrong.
Generic types and collections
Java erases generic type arguments at runtime. body(List.class) therefore gives Jackson no information about the element type. It would build a List of LinkedHashMap objects, not Todo records. You would get no error, only a ClassCastException later when you use an element as a Todo.
To keep the element type, pass a ParameterizedTypeReference. It captures the full type through an anonymous subclass.
import java.util.List;
import org.springframework.core.ParameterizedTypeReference;
List<Todo> findAll() {
return restClient.get()
.uri("/todos")
.retrieve()
.body(new ParameterizedTypeReference<List<Todo>>() {});
}The trailing {} is required. It creates the anonymous subclass that carries the type information. Without it the code does not compile.
An array is an alternative. body(Todo[].class) works with no type reference, because arrays keep their element type at runtime. You can wrap the result with List.of(...) or Arrays.asList(...). The type reference is usually cleaner, especially for nested generics such as Map<String, List<Todo>>.
Getting the status and headers with toEntity()
body() throws away everything except the payload. When the status code, a pagination header, or an ETag matters, use toEntity(). It returns a ResponseEntity<T>, the same type that Spring MVC controllers use.
import java.util.List;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestClient;
record Todo(long id, String title, boolean completed) {}
record TodoPage(List<Todo> items, int total) {}
class TodoPageReader {
private final RestClient restClient;
TodoPageReader(RestClient restClient) {
this.restClient = restClient;
}
TodoPage readPage(int page) {
ResponseEntity<List<Todo>> response = restClient.get()
.uri("/todos?page={page}", page)
.retrieve()
.toEntity(new ParameterizedTypeReference<List<Todo>>() {});
String totalHeader = response.getHeaders().getFirst("X-Total-Count");
int total = totalHeader == null ? 0 : Integer.parseInt(totalHeader);
List<Todo> items = response.getBody() == null ? List.of() : response.getBody();
return new TodoPage(items, total);
}
}The ResponseEntity gives you three things:
getStatusCode()returns the HTTP status. Withretrieve(), a 4xx or 5xx status normally throws before you get here, so fortoEntity()this is usually a 2xx value, such as 200 or 201.getHeaders()returns anHttpHeadersobject.getFirst(name)returns one value ornull. Header names are case-insensitive.getBody()returns the mapped object.
Typed accessors exist for common headers. For example, getHeaders().getLocation() returns a URI for the Location header, and getHeaders().getContentType() returns a MediaType. After a POST that returns 201, getLocation() is the usual way to find the new resource.
When the body is absent
A response can have no body, for example after a 204 No Content or a HEAD request. In that case body(Todo.class) returns null, and toEntity(Todo.class).getBody() returns null. Neither call throws. Code that assumes a non-null result fails later, with a NullPointerException far from the cause.
Handle this on purpose. You can check for null, or wrap the result with Optional.ofNullable. If you never expect a body, use toBodilessEntity() so the intent is clear.
import org.springframework.http.ResponseEntity;
boolean exists(long id) {
ResponseEntity<Void> response = restClient.head()
.uri("/todos/{id}", id)
.retrieve()
.toBodilessEntity();
return response.getStatusCode().is2xxSuccessful();
}Note that this method still throws for a 404, because retrieve() raises an exception for error statuses. The next chapters show how to turn that into false.
How the converter is chosen
Understanding the selection process explains most mapping errors.
- The client sends an
Acceptheader. If you set none, it builds one from the types that its converters can read, which for Jackson includesapplication/json. A default header set on the builder, as in the configuration chapter, overrides this. - The server replies with a
Content-Type. RestClientlooks for a converter that can read your target type from that content type.- If it finds one, it reads the body. If it does not, it throws.
Two failures follow from this:
- No matching converter. The server returns
text/html, perhaps an error page from a proxy, and you asked forTodo. Spring throwsUnknownContentTypeException, a subclass ofRestClientException. Its message names the target type and the content type. It also carries the raw body and status code, so you can log what really arrived. - Matching converter, bad content. The content type is JSON but the structure does not fit your type, for example a string where you declared a
long. Jackson fails andRestClientwraps the failure in aRestClientExceptionwith the message "Error while extracting response for type". The Jackson error is the cause, so readgetCause()to see which field failed.
Error statuses and the response body
Because retrieve() throws for 4xx and 5xx responses, the mapping methods in this chapter run only for successful responses. If you want an error body mapped to your own type, or want to turn a status into a custom exception, add onStatus before the final method. That is the subject of the error handling chapter.
Summary of choices
Use the narrowest method that gives you what you need.
- Need only the data, and the type is not generic:
body(Class). - Need only the data, and the type is generic:
body(new ParameterizedTypeReference<...>() {}). - Need headers or the status:
toEntity(...). - Need no data:
toBodilessEntity(). - Need to see the raw payload while debugging:
body(String.class).
Exercise
An endpoint /todos returns a JSON array of todo objects and an X-Total-Count header. You wrote restClient.get().uri("/todos").retrieve().body(List.class) and later got a ClassCastException when reading an element as a Todo. Why did that happen, and how do you change the call so you also get the header value?
Show answer
List.class carries no element type because Java erases generics, so Jackson built a List of LinkedHashMap objects, and the cast to Todo failed later. Use toEntity(new ParameterizedTypeReference<List<Todo>>() {}). That keeps the element type and returns a ResponseEntity, so response.getHeaders().getFirst("X-Total-Count") gives the header and response.getBody() gives the list.
Exercise
A DELETE request returns 204 No Content. You call .retrieve().body(Todo.class). What does the call return, and which terminal method states your intent better?
Show answer
It returns null without throwing, because the response has no body. toBodilessEntity() states the intent better, because it returns a ResponseEntity<Void> whose status you can check.