Sub topic 2
Reading and Mapping Responses
Assume Java 17, Spring Boot 3.2 or later, basic HTTP, and a configured RestClient bean. RestClient uses a fluent API: build a request, execute it, and convert the response body into a Java type.
Reading Responses
Use body() when you need the decoded body. A Java record is a compact data carrier that Jackson can populate from matching JSON fields.
record Todo(long id, String title, boolean completed) {}
Todo findById(long id) {
return restClient.get()
.uri("/todos/{id}", id)
.retrieve()
.body(Todo.class);
}For status codes and headers, use toEntity(). The result is a ResponseEntity, which contains the status, headers, and body.
Generic types need ParameterizedTypeReference. Java erases generic type information at runtime, so List<Todo>.class cannot be used.
List<Todo> findAll() {
return restClient.get()
.uri("/todos")
.retrieve()
.body(new ParameterizedTypeReference<List<Todo>>() {});
}Sending Request Bodies
Use body() to serialize a Java object into the request body. Set Content-Type when sending JSON. toBodilessEntity() is useful when only the status and headers matter.
record NewTodo(String title) {}
ResponseEntity<Void> create(NewTodo todo) {
return restClient.post()
.uri("/todos")
.contentType(MediaType.APPLICATION_JSON)
.body(todo)
.retrieve()
.toBodilessEntity();
}
void delete(long id) {
restClient.delete()
.uri("/todos/{id}", id)
.retrieve()
.toBodilessEntity();
}The same pattern applies to put(). Choose body() or toEntity() when the server returns useful JSON.
Handling Error Responses
With retrieve(), HTTP 4xx and 5xx responses normally raise a RestClientResponseException. Use onStatus to translate a known status into a domain-specific exception.
Todo findOrThrow(long id) {
return restClient.get()
.uri("/todos/{id}", id)
.retrieve()
.onStatus(status -> status.value() == 404,
(request, response) -> {
throw new TodoNotFoundException(id);
})
.body(Todo.class);
}Catch RestClientResponseException when generic handling needs the status or server-provided error body.
Exercise
Which method should map a JSON response to one Todo, and which type is needed for a list of Todo objects?
Show answer
Use body(Todo.class) for one object and ParameterizedTypeReference<List<Todo>> for the list.