Want to improve as a dev?

I send a short email every workday about Spring topics, API development and improving as a dev.

I understand and agree to the privacy policy

Making Requests using Spring's RestTemplate

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:

@Bean
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("https://swapi.co/api/planets/11/", Planet.class);

System.out.println("------");
System.out.println("Name:");
System.out.println("\t" + planet.getName());
System.out.println("Population:");
System.out.println("\t" + planet.getPopulation());
System.out.println("------");

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 :-)


comments powered by Disqus