Introduction: RestTemplate is a synchronous http client provided by spring. It simplifies interaction with restful webservices. It maps request and response based on java objects which we passed so we no need to worry about data conversions. It is very useful when we are working microservices interaction.

How to use

To use RestTemplate spring-boot-starter-web dependency is required. Add the following dependency.

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

By using @Autowired annotation we can get the default bean of RestTemplate.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class SimpleService {

    @Autowired
    private RestTemplate restTemplate;

    public void getTodoDataById() {
        String url = "https://jsonplaceholder.typicode.com/todos/1";
        String response =restTemplate.getForObject(url, String.class);
System.out.println("response: "+response);
    }
}

https://jsonplaceholder.typicode.com/todos/1 is open source endpoint that gives below data.

{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}

Added String.class in above example, it converts data into string format.

For demonstrating RestTemplate CRUD operations we are using open source json provider.

Lets take /todos endpoint , it have 4 attributes so create a java object with four fields.

@Data
public class Todos {
private Long id;
private Long userid;
private String title;
private boolean completed;
}

@Data annotation used to reduces boilerplate plate code. Which means no need to generate setters, getters, toString, equals, and hashCode methods for Todos class fields.

Now replace the first example with Todos class.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class SimpleService {

    @Autowired
    private RestTemplate restTemplate;

    public Todos getTodoDataById() {
        String url = "https://jsonplaceholder.typicode.com/todos/1";
        return restTemplate.getForObject(url, Todos.class);

    }
}

Hit endpoint in the browser, now it gives data in json format.

POST data: To persist or save the data use postForObject or exchange methods.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class SimpleService {

    @Autowired
    private RestTemplate restTemplate;

    public Todos postTodoData(@RequestBody Todos todos) {
        String url = "https://jsonplaceholder.typicode.com/todos";
        return restTemplate.postForObject(url,todos, Todos.class);

    }
}

GET data: Get the data from an endpoint use getForObject or exchange methods.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class SimpleService {

    @Autowired
    private RestTemplate restTemplate;

    public Todos getTodoData(@PathVariable Long id) {
        String url = "https://jsonplaceholder.typicode.com/todos/"+id;
        return restTemplate.getForObject(url,Todos.class);

    }
}

PUT data: put or exchange methods are required to update the data.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class SimpleService {

    @Autowired
    private RestTemplate restTemplate;

    public Todos updateTodoData(@RequestBody Todos todos) {
        String url = "https://jsonplaceholder.typicode.com/todos/"+todos.getId();
        return restTemplate.put(url,todos, Todos.class);

    }
}

DELETE data : delete or exchange methods are useful for performing delete operation.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class SimpleService {

    @Autowired
    private RestTemplate restTemplate;

    public void deleteTodo(@PathVariable Long id) {
        String url = "https://jsonplaceholder.typicode.com/todos/"+id;
         restTemplate.delete(url);

    }
}

Adding Headers: HttpHeaders are used to add headers to the request.

RestTemplate restTemplate = new RestTemplate();

String url = "https://api.example.com/data";
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer add-token-here");
headers.set("customHeader", "Custom header value");

HttpEntity<String> requestEntity = new HttpEntity<>(headers);

ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);

String responseBody = responseEntity.getBody();

Adding parameters : Use UriComponentsBuilder to add parameters to the endpoint.

HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type", "application/json");

UriComponentsBuilder builder = UriComponentsBuilder.fromUriString("https://example.com/sampleapi/")
        .queryParam("param1", "value1")
        .queryParam("param2", "value2");

HttpEntity<String> entity = new HttpEntity<>(headers);

ResponseEntity<String> response = restTemplate.exchange(
        builder.toUriString(),
        HttpMethod.GET,
        entity,
        String.class
);

Make a request with Headers and Request Body

Create a HttpHeaders to set the header values and using HttpEntity we can set header and RequestBody to a http request.

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

public class RestTemplateExample {
@Autowired
RestTemplate restTemplate;

    public void sendRequest(@RequestBody Todos todo) {
        
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer your_token_here");

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

        HttpEntity<Todos> entity = new HttpEntity<>(todo, headers);

        restTemplate.postForObject(url, entity, String.class);
    }
}

Refer the following article for Resttemplate customization.