Sub topic 1
What RestClient Is
RestClient is a synchronous HTTP client with a fluent API. Spring Framework 6.1 introduced it, and Spring Boot 3.2 and later support it. You call it from ordinary blocking code, such as a service method, and it returns the result directly.
Prerequisites
This chapter assumes you know the following:
- Java 17 or later, including records and lambdas.
- Basic Spring Boot: beans,
@Configuration, and dependency injection. - HTTP basics: methods, status codes, and headers.
- JSON as a data format.
You need a Spring Boot 3.2+ project with spring-boot-starter-web. The starter brings in Jackson, which converts between JSON and Java objects.
Why RestClient exists
Before Spring 6.1, a Spring application that wanted to call another HTTP service had two main choices:
RestTemplateis synchronous, but its API is a large set of overloaded methods such asgetForObjectandpostForEntity.WebClienthas a fluent API, but it is reactive. It belongs to Spring WebFlux and returnsMonoandFluxtypes, even when you only want a blocking call.
RestClient fills the gap. It keeps the blocking model of RestTemplate and uses the fluent, chained style of WebClient. It reuses the same message converters and request infrastructure that RestTemplate uses, so existing JSON mapping and configuration carry over.
The next chapter compares the three clients in more detail. For now, the point is that RestClient is the current choice for blocking calls in new code.
The shape of a call
Every RestClient call is a chain of steps. Each step narrows what you can do next:
- Pick the HTTP method:
get(),post(),put(),delete(). - Set the target with
uri(...). - Optionally add headers or a body.
- Call
retrieve()to send the request and get a response specification. - Read the result with
body(...)ortoBodilessEntity().
The request is not sent until you call retrieve(), so you can build up the request in as many steps as you need.
A first example
The example below is a complete class that fetches one todo item from a public test API. It uses the static RestClient.create(...) method, which builds a client with default settings and a base URL.
import org.springframework.web.client.RestClient;
public class FirstCall {
record Todo(long id, String title, boolean completed) {}
public static void main(String[] args) {
RestClient client = RestClient.create("https://jsonplaceholder.typicode.com");
Todo todo = client.get()
.uri("/todos/{id}", 1)
.retrieve()
.body(Todo.class);
System.out.println(todo);
}
}Running it prints a line like Todo[id=1, title=delectus aut autem, completed=false]. Here is what each part does:
RestClient.create(String)makes a client whose base URL is prepended to every relative URI.{id}is a URI template variable. Spring replaces it with1and encodes the value safely.retrieve()sends the request and checks the status code.body(Todo.class)reads the JSON response and converts it into aTodorecord. Jackson maps JSON fields to record components by name.
The method blocks until the full response arrives. Nothing else is needed to get the value, and there is no subscribe or block call.
Where RestClient fits in a Spring Boot app
In a real application you rarely call RestClient.create directly. Spring Boot auto-configures a RestClient.Builder bean. You inject that builder, set a base URL and default headers, and build the client once. The builder is also what Boot's customizers and test tools hook into, which later chapters use.
Two behaviors are worth knowing from the start:
- Errors become exceptions. If the server answers with a 4xx or 5xx status,
retrieve()leads to aRestClientResponseExceptionwhen you read the body. You do not get a null result. Later chapters cover how to handle this. - A client is reusable. A
RestClientis thread-safe once built. Create it once, share it, and call it from many threads.
Common mistakes
- Using
RestClientwithout Spring Boot 3.2 or Spring Framework 6.1. The class does not exist in earlier versions. Check your dependency versions first. - Building the URI with string concatenation. Writing
"/todos/" + idskips encoding. Use template variables such as{id}. - Expecting a null on 404. A 404 raises an exception. It does not return null.
Exercise
A teammate wants to call another service from a blocking service method in a Spring Boot 3.3 application. They are choosing between RestTemplate, WebClient, and RestClient. Why is RestClient a good fit, and which method call actually sends the request?
Show answer
RestClient is synchronous like RestTemplate, so it works in blocking code, and it has the fluent API that RestTemplate lacks. WebClient would force them into reactive types they do not need. The request is sent when retrieve() is called, and body(...) then reads the response.