RestClient in Spring Framework 6.1

Note: This is work in progress

Spring Framework 6.1 M2 debuts the RestClient, a fresh synchronous HTTP client. As its name implies, the RestClient provides the smooth WebClient API while leveraging the foundation of RestTemplate. With this we have 3 HTTP clients in Spring Framework.

  1. RestTemplate
  2. Web Client
  3. Rest Client (new)


Around fourteen years ago, Spring Framework 3.x introduced RestTemplate and it quickly became default standard to make HTTP requests in Spring. But it also because complex after exposing multiple HTTP methods.

// Create RestTemplate object with defaults
var restTemplate = new RestTemplate();

// Build headers
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Bearer " + token);
var httpEntity=HttpEntity<>(headers);

// Make request
HttpEntity<UserInfo> response ="", GET, httpEntity, UserInfo.class);

// RestTemplate converts response to given object type
var userInfo=response.getBody();
Web Client

In Spring Framework 5.x, the team added a fluent API for the reactive WebClient while keeping RestTemplate in maintenance mode. The developers were advised to WebClient with block() for synchronous behavior

// Get WebClient
var uriSpec = webClient.get().uri("");

// Add Auth Headers
uriSpec.headers(httpHeaders -> httpHeaders.add("Authorization", "Bearer " + token));

// Make request and get Response

Rest Client

The new RestClient that will be part of Spring Framework 6.1 or later offers API similar to WebClient and much easier to work with. As per official docs “RestClient is a Client to perform HTTP requests, exposing a fluent, synchronous API over underlying HTTP client libraries such the JDK HttpClient, Apache HttpComponents, and others

Meaning it uses JDK HttpClient under. Checkout the blog post HTTP Requests in Java to learn more about JDK HttpClient.

Creating RestClient

You can create new client by using create() method

// Create new client
var restClient = RestClient.create();

// Make HTTP Request
Employee employee = restClient.get()

or via RestClient.Builder builder() method. If you want to apply default values to builder, you can pass map of values. You can also pass global headers or request handlers using defaultHeader() and defaultRequest() methods. Check official docs for details on the API

// Create new client via builder
 var factory = new DefaultUriBuilderFactory(baseUrl);
 var restClient = RestClient.builder().uriBuilderFactory(factory).build();

// Make HTTP Request
var employee = restClient.get()

You can also use existing RestTemplate to initialize RestClient.

// Create new client by passing RestTemplate instance
var restClient = RestClient.create(restTemplate);
GET Requests

Pavan Kumar Jadda
Pavan Kumar Jadda
Articles: 36

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.