1. Introduction
RestClient is a synchronous HTTP client introduced in Spring Framework 6.1 M2 that supersedes RestTemplate. A synchronous HTTP client sends and receives HTTP requests and responses in a blocking manner, meaning it waits for each request to complete before proceeding to the next one.
In this tutorial, we’ll explore what RestClient offers, and how it compares to RestTemplate.
2. RestClient and RestTemplate
RestTemplate, as the name suggests, is built on a template design pattern. It’s a behavioral design pattern that defines the skeleton of an algorithm in a method, allowing subclasses to provide specific implementations for certain steps. While it’s a powerful pattern, it creates a need for overloading, which can be inconvenient.
To improve on this, RestClient features a fluent API. A fluent API is a design pattern that allows method chaining in a way that makes the code more readable and expressive by sequentially calling methods on an object, often without the need for intermediate variables.
Let’s start with creating a basic RestClient:
RestClient restClient = RestClient.create();
3. Simple Fetching With HTTP Request Methods
Similar to RestTemplate, or any other rest client, RestClient allows us to make HTTP calls with request methods. Let’s walk through different HTTP methods to create, retrieve, modify, and delete resources.
We’ll operate on an elementary Article class:
public class Article {
Integer id;
String title;
// constructor and getters
}
3.1. Use GET to Retrieve Resources
We’ll use the GET HTTP method to request and retrieve data from a specified resource on a web server without modifying it. It’s primarily employed for read-only operations in web applications.
To start, let’s get a simple String as the response without any serialization to our custom class:
String result = restClient.get()
.uri(uriBase + "/articles")
.retrieve()
.body(String.class);
3.2. Use POST to Create a Resource
We’ll use the POST HTTP method to submit data to a resource on a web server, often to create new records or resources in web applications. Unlike the GET method, which retrieves data, POST is designed for sending data to be processed by the server, such as when submitting a web form.
The URI should define what resource we want to process.
Let’s send a simple Article with an ID equal to 1 to our server:
Article article = new Article(1, "How to use RestClient");
ResponseEntity<Void> response = restClient.post()
.uri(uriBase + "/articles")
.contentType(APPLICATION_JSON)
.body(article)
.retrieve()
.toBodilessEntity();
Because we specified the “APPLICATION_JSON” content type, the instance of the Article class will be automatically serialized to JSON by the Jackson library under the hood. In this example, we ignore the response body using the toBodilessEntity() method. A POST endpoint doesn’t need to, and often doesn’t, return any payload.
3.3. Use PUT to Update a Resource
Next, we’ll look at the PUT HTTP method employed to update or replace an existing resource with the data provided. It’s commonly used for modifying existing entities, or other resources in web applications. Typically, we need to specify the updated resource, ensuring a complete replacement.
Let’s modify the article we created in the previous paragraph. The URI we provide should identify the resource we want to change:
Article article = new Article(1, "How to use RestClient even better");
ResponseEntity<Void> response = restClient.put()
.uri(uriBase + "/articles/1")
.contentType(APPLICATION_JSON)
.body(article)
.retrieve()
.toBodilessEntity();
Similar to the previous paragraph, we’ll rely on RestClient to serialize our payload and ignore the response.
3.4. Use DELETE to Remove a Resource
We’ll use the DELETE HTTP method to request the removal of a specified resource from a web server. Similar to GET endpoints, we usually don’t provide any payload for the request, and rely on parameters encoded in the URI:
ResponseEntity<Void> response = restClient.delete()
.uri(uriBase + "/articles/1")
.retrieve()
.toBodilessEntity();
4. Deserializing Response
We often want to serialize the request and deserialize the response to some class we can efficiently operate on. The RestClient is equipped with the ability to perform JSON-to-object conversions, a functionality powered by the Jackson library.
Moreover, we can use all data types supported by RestTemplate because of the shared utilization of message converters.
Let’s retrieve an article by its ID, and serialize it to the instance of the Article class:
Article article = restClient.get()
.uri(uriBase + "/articles/1")
.retrieve()
.body(Article.class);
Specifying the class of the body is a bit more complicated when we want to get an instance of some generic class, like List. For example, if we want to get all the articles, we’ll get the List
We don’t even need to specify the generic type, Java will infer the type for us:
List<Article> articles = restClient.get()
.uri(uriBase + "/articles")
.retrieve()
.body(new ParameterizedTypeReference<>() {});
5. Parsing Response With Exchange
The RestClient includes the exchange() method for handling more advanced situations by granting access to the underlying HTTP request and response. As such, the library won’t apply default handlers, and we must process the status ourselves.
Let’s say the service we’re communicating with returns a 204 status code when no articles are in the database. Because of that slightly nonstandard behavior, we want to handle it in a special way. We’ll throw an ArticleNotFoundException exception when the status code is equal to 204, and also a more generic exception when the status code isn’t equal to 200:
List<Article> article = restClient.get()
.uri(uriBase + "/articles")
.exchange((request, response) -> {
if (response.getStatusCode().isSameCodeAs(HttpStatusCode.valueOf(204))) {
throw new ArticleNotFoundException();
} else if (response.getStatusCode().isSameCodeAs(HttpStatusCode.valueOf(200))) {
return objectMapper.readValue(response.getBody(), new TypeReference<>() {});
} else {
throw new InvalidArticleResponseException();
}
});
Because we’re working with a raw response here, we also need to deserialize the body of the response ourselves using ObjectMapper.
6. Error Handling
By default, when RestClient encounters a 4xx or 5xx status code in the HTTP response, it raises an exception that’s a subclass of RestClientException. We can override this behavior by implementing our status handler.
Let’s write one that will throw a custom exception when we can’t find the article:
Article article = restClient.get()
.uri(uriBase + "/articles/1234")
.retrieve()
.onStatus(status -> status.value() == 404, (request, response) -> {
throw new ArticleNotFoundException(response)
})
.body(Article.class);
7. Building RestClient From RestTemplate
RestClient is the successor of RestTemplate, and in older codebases, we’re very likely to encounter implementation using RestTemplate.
Fortunately, it’s straightforward to create a RestClient instance with a configuration of the old RestTemplate:
RestTemplate oldRestTemplate;
RestClient restClient = RestClient.create(oldRestTemplate);
8. Conclusion
In this article, we focused on the RestClient class, the successor of RestTemplate, as a synchronous HTTP client. We learned how to use its fluent API for both simple and complicated use cases. Next, we started rounding up all the HTTP methods, and then moved on to response serialization and error-handling topics.
As usual, all the code examples are available over on GitHub.