Spring RestTemplate Tutorial

The RestTemplate class within the Spring Framework is a simple HTTP client that enables your code to send HTTP requests and handle HTTP responses. This tutorial will demonstrate how to use RestTemplate to send various types of HTTP requests.

Create Spring Boot App

RestTemplate is a component of the Spring Framework and is typically utilized for interacting with RESTful web services. Assuming that you have already created a project, otherwise, you may refer to a simple tutorial on creating a new RESTful web service project using the Spring Framework.

Add Pom.XML Dependency

To make RestTemplate available in your Spring Boot application, you need to add the following Spring Boot Starter dependency to your pom.xml file.

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-web</artifactId>
</dependency>

For the purpose of this tutorial, I have created a simple Spring Boot project using the link provided. After adding the Spring Boot Starter Web Dependency, my pom.xml file now looks like the one shown below.

Complete pom.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.1.1.RELEASE</version>
  <relativePath/> <!-- lookup parent from repository -->
 </parent>
 <groupId>com.appsdeveloperblog.examples.RestTemplateExample</groupId>
 <artifactId>RestTemplateExample</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <name>RestTemplateExample</name>
 <description>Demo project for Spring Boot</description>

 <properties>
  <java.version>1.8</java.version>
 </properties>

 <dependencies>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
  </dependency>

  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
  </dependency>
 </dependencies>

 <build>
  <plugins>
   <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
   </plugin>
  </plugins>
 </build>

</project>

Create RestTemplate Bean

To utilize Dependency Injection and the @Autowired annotation to inject RestTemplate into your RestController or Service classes, you need to create a RestTemplate bean in the file that includes the public static void main(String[] args) function. Here’s an example of my Spring Boot application file that creates the RestTemplate Bean.

package com.appsdeveloperblog.examples.RestTemplateExample.RestTemplateExample;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class RestTemplateExampleApplication {

    public static void main(String[] args) {
        SpringApplication.run(RestTemplateExampleApplication.class, args);
    }

    @Bean
    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }

}

Now that I have created the RestTemplate bean, I can utilize it in my @RestController or @Service classes.

RestTemplate HTTP GET Example

Let’s take a look at how we can utilize RestTemplate to send an HTTP GET request to a public Web Service Endpoint that returns a JSON Array consisting of JSON Objects.

Public Web Service Endpoint URL

https://jsonplaceholder.typicode.com/todos

Return JSON Array

To retrieve a list of TodoModel objects using HTTP GET request, you can refer to the following code example:

ResponseEntity<List<TodoModel>> response = restTemplate.exchange(theUrl, HttpMethod.GET, null, new ParameterizedTypeReference<List<TodoModel>>() {
});

List<TodoModel> todoList = response.getBody();

We will now examine the entire @RestController class that utilizes RestTemplate. An instance of RestTemplate is injected into our Controller class using the @Autowired annotation.

package com.appsdeveloperblog.examples.RestTemplateExample.RestTemplateExample;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
 
@RestController
@RequestMapping("/todos")
public class TodoController {

    @Autowired
    RestTemplate restTemplate;

    @GetMapping
    public List<TodoModel> getTodos() {

        String theUrl = "https://jsonplaceholder.typicode.com/todos";

        ResponseEntity<List<TodoModel>> response = restTemplate.exchange(theUrl, HttpMethod.GET, null, new ParameterizedTypeReference<List<TodoModel>>() {
        });

        List<TodoModel> todoList = response.getBody();

        return todoList;

    }
}

Please note that when the Web Service Endpoint above is called, it returns a JSON Array of JSON Objects. Each JSON object is converted into a TodoModel object using the TodoModel Java class. It’s important to note that the TodoModel class is not part of RestTemplate. If the Web Service Endpoint were to return a different list of objects, we would need to create a different model class for it. Your RESTful Web Service will most likely return a different JSON, so you’ll need to create a different model class for that. The source code for the TodoModel class, which is returned by the public Web Service Endpoint above, is provided below.

TodoModel Java Class

/*
 * To change this license header, choose License Headers in Project Properties.

package com.appsdeveloperblog.examples.RestTemplateExample.RestTemplateExample;

public class TodoModel {

    private String userId;
    private int id;
    private String title;
    private boolean completed;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public boolean isCompleted() {
        return completed;
    }

    public void setCompleted(boolean completed) {
        this.completed = completed;
    }

}

Return a Single JSON Object

The code example below will send an HTTP GET request to the public RESTful Web Service Endpoint mentioned above and retrieve a single JSON object, which will be converted into a Java class called TodoModel. The source code for the TodoModel class is provided above.

package com.appsdeveloperblog.examples.RestTemplateExample.RestTemplateExample;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
 
@RestController
@RequestMapping("/todos")
public class TodoController {

    @Autowired
    RestTemplate restTemplate;

    @GetMapping(path="/{id}")
    public TodoModel getTodo(@PathVariable String id) {

        String theUrl = "https://jsonplaceholder.typicode.com/todos/" + id;

        ResponseEntity<TodoModel> response = restTemplate.exchange(theUrl, HttpMethod.GET, null, TodoModel.class );

        TodoModel todoList = response.getBody();

        return todoList;
    }
}

Return a Plain JSON String

In the examples provided above, we utilized RestTemplate to transform the JSON located in the HTTP Response’s body into a Java object. Alternatively, it is feasible to receive a plain JSON string.

@GetMapping(path="/json")
public String getTodosJson() {

    String theUrl = "https://jsonplaceholder.typicode.com/todos";

    ResponseEntity<String> response = restTemplate.exchange(theUrl, HttpMethod.GET, null, String.class);
 
    return response.getBody();

}

RestTemplate HTTP POST Request

RestTemplate can also be used to send HTTP POST requests. Below is an example of a RestController method that accepts an HTTP POST request and uses RestTemplate to perform an HTTP POST request as well.

@PostMapping
public TodoModel createTodo(@RequestBody TodoModelRequestBody todoModelRequest)
{
    String theUrl = "";
    
    HttpEntity<TodoModelRequestBody> requestEntity = new HttpEntity<>(todoModelRequest);
    
    ResponseEntity<TodoModel> response = restTemplate.exchange(theUrl, HttpMethod.POST, requestEntity, TodoModel.class );
    
    return response.getBody();
}

RestTemplate HTTP PUT Request

Just like sending an HTTP POST request, you can also use RestTemplate to send an HTTP PUT request. Here’s an example of how you can send an HTTP PUT request using the RestTemplate class:

@PutMapping(path="/{id}")
public TodoModel updateTodo(@RequestBody TodoModelRequestBody todoModelRequest, 
        @PathVariable String id)
{
    String theUrl = "https://jsonplaceholder.typicode.com/todos/" + id;
    
    HttpEntity<TodoModelRequestBody> requestEntity = new HttpEntity<>(todoModelRequest);
    
    ResponseEntity<TodoModel> response = restTemplate.exchange(theUrl, HttpMethod.PUT, requestEntity, TodoModel.class );
    
    return response.getBody();
}

RestTemplate HTTP DELETE Request

You can use RestTemplate to send HTTP DELETE request as well. RestTemplate class has a delete() method which makes the code even shorter.

String theUrl = "https://jsonplaceholder.typicode.com/todos/" + id;
restTemplate.delete(theUrl);

How to Include HTTP Headers

RestTemplate can be used to send HTTP requests with one or more HTTP request headers. Here’s an example of creating an HTTPHeaders object and setting the Accept HTTP header.

HttpHeaders headers = new HttpHeaders();
headers.setAccept(new ArrayList<>(Arrays.asList(MediaType.APPLICATION_JSON)));

Here is the updated HTTP POST request which includes HTTP headers:

@Autowired
RestTemplate restTemplate;

@GetMapping(produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE})
public List<TodoModel> getTodos() {

    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(new ArrayList<>(Arrays.asList(MediaType.APPLICATION_JSON)));

    HttpEntity<List<TodoModel>> entity = new HttpEntity<>(headers);
    String theUrl = "https://jsonplaceholder.typicode.com/todos";

    ResponseEntity<List<TodoModel>> response = restTemplate.exchange(theUrl, HttpMethod.GET, entity, new ParameterizedTypeReference<List<TodoModel>>() {
    });

    List<TodoModel> todoList = response.getBody();

    return todoList;
}

How to read HTTP Headers

Below is a little code snippet that shows how to read HTTP Headers from an HTTP Response.

String theUrl = "https://jsonplaceholder.typicode.com/todos";

ResponseEntity<String> response = restTemplate.exchange(theUrl, HttpMethod.GET, null, String.class);
HttpHeaders headers = response.getHeaders();
List<MediaType> supportedMediaTypes = headers.getAccept();

To retrieve a custom header from a list, you can use the following code snippet:

HttpHeaders headers = response.getHeaders();
List<String> headerValues = headers.get("<CUSTOM HEADER NAME HERE>");

Conclusion

I hope this tutorial on how to use RestTemplate has been helpful to you. If you’re interested in learning more about building RESTful web services, please check out our other tutorials in the Spring Boot and Spring MVC section. And if you enjoy learning by watching a series of step-by-step video lessons, take a look at the list of video courses below.

Happy learning!

Leave a Reply

Your email address will not be published. Required fields are marked *