Spring RestTemplate Tutorial

The RestTemplate class in Spring Framework is a very easy to use HTTP Client which allows your code to send HTTP Request and also handle the HTTP Response. In this tutorial you will learn how to use RestTemplate to send different types of HTTP Requests.

Create Spring Boot App

RestTemplate is part of Spring Framework and is usually used with RESTful Web Services. I assume you already have a project created but if you do not have, then follow this very simple tutorial to learn how to Create a New RESTful Web Service Project with Spring Framework.

Add Pom.XML Dependency

To make RestTemplate available in your Spring Boot application you will need to have the following Spring Boot Starter dependency added to your pom.xml

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

For the purpose of this tutorial I have created a very simple Spring Boot project using the link above and after adding the Spring Boot Starter Web Dependency my complete pom.xml file how looks like the one 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

For you to be able to use Dependency Injection and the @Autowired annotation to inject the RestTemplate into your RestController or Service classes, create a RestTemplate bean in the file which contains the public static void main(String[] args) function. Below is an example of my Spring Boot application file which 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 when I have the RestTemplate bean created I can use it in my @RestController or @Service classes.

RestTemplate HTTP GET Example

Let’s have have a look at how we can use RestTemplate to send HTTP GET request to a public Web Service Endpoint which returns a JSON Array of JSON Objects.

Public Web Service Endpoint URL

https://jsonplaceholder.typicode.com/todos

Return JSON Array

To send HTTP GET Request which gets back a List of TodoModel objects you can use the following code example:

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

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

Let’s have a look at the complete @RestController class which uses RestTemplate, an instance of which is injected to our Controller class with an @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 above Web Service Endpoint is called it returns a JSON Array of JSON Objects. Each JSON object is converted into a TodoModel object. The TodoModel Java class is not part of RestTemplate. If the above Web Service Endpoint would be returning a different list of object, then we would create a different model class. Your RESTful Web Service most likely will be returning a different JSON. So you will need to create a different model class for that. The source code of the TodoModel class which the above public Web Service Endpoint returns is 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 below code example will send a HTTP GET request to the above mentioned public RESTful Web Service Endpoint and will get back a Single JSON Object which will be converted into a TodoModel Java class. The source code of TodoModel Java class is 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 above examples, we used RestTemplate to convert the JSON in the body of HTTP Response into a Java object. It is also possible to simply get 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

You can use RestTemplate to send HTTP Post request as well. Below is an example of RestController method which accepts HTTP Post Request and then uses RestTemplate to perform 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

Similarly to sending HTTP POST Request, you can make RestTemplate send HTTP Put request. Help is an example of how you can send HTTP Put request with 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

You can use RestTemplate to send HTTP Request that contains one or multiple HTTP Request Headers. Below is an example of how to create an HTTPHeaders object and set the Accept HTTP Header.

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

and here is 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 get a custom header from the list you can use the following code snippet:

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

I hope this tutorial on how to use RestTemplate was helpful to you. If you are interested to learn more about building RESTful Web Services please check other tutorial in SpringBoot and Spring MVC section and if you enjoy learning by watching a series of step by step video lessons then check the below list of video courses.

Happy learning!