Making Requests using Spring's RestTemplate

Last Update: 09.02.2018. By Jens in Newsletter | Spring Boot | Spring MVC

The RestTemplate is a little helper class that makes calling web requests an easier. Instead of wrangling with protocols and transformation by ourselves, we get that out of the box by Spring MVC.

We can directly create an instance of it, or we can use the RestTemplateBuilder and make it also available as Spring bean for dependency injection.

I haven’t deployed the Kanban API yet, so we are going to use Swapi - The Star Wars API - for a test.

Setting up the RestTemplate using the RestTemplateBuilder looks like:

public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) {
    ClientHttpRequestInterceptor interceptor = (request, body, execution) -> {
        request.getHeaders().add("user-agent", "spring");
        return execution.execute(request, body);
    return restTemplateBuilder.additionalInterceptors(interceptor).build();

Like with service side requests, the RestTemplate also supports MessageConverters and interceptors on the client side. They do the same as on the server side.

In the above example, we add an interceptor which adds a user-agent string on each request. Swapi checks for one so we define an arbitrary one.

The center of RestTemplate is the exchange method. All other are convenience methods. We will use the getForObject which make a GET request to the given URL and tries to transform the result into our Planet class.

Planet planet = restTemplate.getForObject("", Planet.class);

System.out.println("\t" + planet.getName());
System.out.println("\t" + planet.getPopulation());

The URL string supports placeholder in the form {name}, which are resolved against the urlVariable map on the other method signature. The key in the map is the name of the placeholder.

As an exercise combine it with the command line runner from yesterdays mail and tell me which planet it is :-)

Want content like this in your inbox each workday irregularly? No BS, spam or tricks... just useful content:

I understand and agree to the privacy policy