Spring Boot RestTemplate is by far the easiest and most efficient way of consuming RESTful APIs using Spring Boot.

In a typical microservices architecture, different applications talk to each other using RESTful APIs. If these microservices are built using a framework such as Spring Boot, it becomes absolutely vital to have knowledge about RestTemplate.

In this post, we will understand how we can use Spring Boot RestTemplate to make API Calls.

1 – RestTemplate GET Resource

First off, we will be understanding how to issue a HTTP GET request using RestTemplate and processing the response we receive.

For the purposes of our demo, we will be using some Fake APIs. These APIs are available on https://jsonplaceholder.typicode.com/.

There are various resources available as part of these Fake APIs such as ToDo, Posts, Comments and so on. Also, it supports all the common HTTP Methods such as GET, POST, PUT and DELETE.

1.1 – Plain JSON

The RestTemplate implementation has a method known as exchange(). This method takes the uri, method type and the expected output class as input and returns the response from the API Call.

We can make a GET request using this exchange() method as below. In response, we receive the JSON string.

private void callGetToDoWithString() {

		RestTemplate restTemplate = new RestTemplate();

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

		HttpHeaders headers = new HttpHeaders();
		headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
		HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);

		ResponseEntity<String> result = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class);

		System.out.println("###########################################");
		System.out.println("Printing GET Response in String");
		System.out.println("###########################################");

		System.out.println(result);
}

The response is as below:

###########################################
Printing GET Response in String
###########################################
<200,{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
},[Date:"Sat, 18 Jan 2020 03:39:33 GMT"

Basically, the response String is wrapped within a ResponseEntity class. The ResponseEntity class contains the status code as well as other information pertaining to the call.

1.2 – POJO Instead of JSON

RestTemplate is very flexible in its approach. As a result, if we want, we can directly map the response object to a POJO.

In this case, we will first have to define the ToDo class in our consumer application.

class ToDo {

	private int userId;

	private int id;

	private String title;

	private boolean completed;

	public int getUserId() {
		return userId;
	}

	public void setUserId(int 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;
	}

	@Override
	public String toString() {
		return "ToDo{" +
				"userId=" + userId +
				", id=" + id +
				", title='" + title + '\'' +
				", completed=" + completed +
				'}';
	}
}

We can now use the ToDo class in our call to the exchange() method.

private void callGetToDoWithPOJO() {
		RestTemplate restTemplate = new RestTemplate();

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

		HttpHeaders headers = new HttpHeaders();
		headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
		HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);

		ResponseEntity<ToDo> result = restTemplate.exchange(uri, HttpMethod.GET, entity, ToDo.class);

		System.out.println("###########################################");
		System.out.println("Printing GET Response in POJO");
		System.out.println("###########################################");

		System.out.println(result.toString());
}

This time the ResponseEntity wraps the ToDo object. Below is the response from this call.

###########################################
Printing GET Response in POJO
###########################################
<200,ToDo{userId=1, id=1, title='delectus aut autem', completed=false},[Date:"Sat, 18 Jan 2020 03:39:33 GMT"

2 – RestTemplate POST Resource

As already mentioned, exchange() method is flexible enough to work with different HTTP Methods.

We can use it to issue a POST request to create a new resource on the server as below:

	private void callPostToDo() {
		RestTemplate restTemplate = new RestTemplate();

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

		ToDo newTodo = new ToDo();
		newTodo.setUserId(1);
		newTodo.setTitle("Test Todo");
		newTodo.setCompleted(false);

		HttpHeaders headers = new HttpHeaders();
		headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
		HttpEntity<ToDo> entity = new HttpEntity<ToDo>(newTodo, headers);

		ResponseEntity<ToDo> result = restTemplate.exchange(uri, HttpMethod.POST, entity, ToDo.class);

		System.out.println("###########################################");
		System.out.println("Printing POST Response");
		System.out.println("###########################################");

		System.out.println(result);
}

Notice here that we first create a new instance of ToDo. Then, we wrap this ToDo object inside a HTTPEntity object. Finally, we pass this HTTPEntity object as part of our call to the exchange() method. Then, the response comes back in a ResponseEntity object as always.

Below is the response for this example.

###########################################
Printing POST Response
###########################################
<201,ToDo{userId=1, id=201, title='Test Todo', completed=false},[Date:"Sat, 18 Jan 2020 03:39:34 GMT"

Notice that it is quite similar to the earlier response from the GET request. The only change is the HTTP Status Code of 201 (CREATED).

3 – RestTemplate PUT Resource

The HTTP PUT method is used to update a resource on the server. With RestTemplate’s exchange() method, you can simply issue a PUT request just by changing the input method type to the call.

private void callPutToDo() {
		RestTemplate restTemplate = new RestTemplate();

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

		ToDo newTodo = new ToDo();
		newTodo.setUserId(1);
		newTodo.setId(1);
		newTodo.setTitle("Updated ToDo");
		newTodo.setCompleted(false);

		HttpHeaders headers = new HttpHeaders();
		headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
		HttpEntity<ToDo> entity = new HttpEntity<ToDo>(newTodo, headers);

		ResponseEntity<ToDo> result = restTemplate.exchange(uri, HttpMethod.PUT, entity, ToDo.class);

		System.out.println("###########################################");
		System.out.println("Printing PUT Response");
		System.out.println("###########################################");

		System.out.println(result);
}

Here also, we setup a new ToDo object. However, this time, we are trying to update the value of the title attribute for ToDo # 1.

Below is the response.

###########################################
Printing PUT Response
###########################################
<200,ToDo{userId=1, id=1, title='Updated ToDo', completed=false},[Date:"Sat, 18 Jan 2020 03:39:34 GMT"

4 – RestTemplate DELETE Resource

The HTTP DELETE method is pretty similar to GET except for the fact that mostly we don’t get a response back except maybe the Status Code.

With the exchange() method, we can very easily issue the DELETE call as well.

private void callDeleteToDo() {

		RestTemplate restTemplate = new RestTemplate();

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

		HttpHeaders headers = new HttpHeaders();
		headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
		HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);

		ResponseEntity<String> result = restTemplate.exchange(uri, HttpMethod.DELETE, entity, String.class);

		System.out.println("###########################################");
		System.out.println("Printing DELETE Response");
		System.out.println("###########################################");

		System.out.println(result);

}

Below is the response.

###########################################
Printing DELETE Response
###########################################
<200,{},[Date:"Sat, 18 Jan 2020 03:39:35 GMT", Content-Type:"application/json; charset=utf-8"

Notice how we receive an empty response. Basically, in this approach, only the Status Code of 200 is returned signifying a successful operation.

5 – RestTemplate getForObject()

Apart from the exchange() method, RestTemplate also has several other methods.

Although it is not possible to look at all the methods in this post, we can check out some of the important ones.

The getForObject() method allows you to directly return the underlying object without the ResponseEntity wrapping.

private void callGetForObject() {

		RestTemplate restTemplate = new RestTemplate();

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

		ToDo toDo = restTemplate.getForObject(uri, ToDo.class);

		System.out.println("###########################################");
		System.out.println("Printing GET FOR OBJECT Response");
		System.out.println("###########################################");

		System.out.println(toDo);
}

Here, we only pass the URI and the expected response class to getForObject() method.

The response is as below:

###########################################
Printing GET FOR OBJECT Response
###########################################
ToDo{userId=1, id=1, title='delectus aut autem', completed=false}

6 – RestTemplate getForEntity()

Another useful method within the RestTemplate class is the getForEntity() method. Basically, this method returns a ResponseEntity object with the underlying resource object.

See below example:

private void callGetForEntity() {

		RestTemplate restTemplate = new RestTemplate();

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

		ResponseEntity result = restTemplate.getForEntity(uri, ToDo.class);

		System.out.println("###########################################");
		System.out.println("Printing GET FOR ENTITY Response");
		System.out.println("###########################################");

		System.out.println(result);
}

The response has the ToDo object wrapped inside the ResponseEntity.

###########################################
Printing GET FOR ENTITY Response
###########################################
<200,ToDo{userId=1, id=1, title='delectus aut autem', completed=false},[Date:"Sat, 18 Jan 2020 04:09:25 GMT"

Conclusion

Spring Boot RestTemplate is an extremely versatile approach towards consuming RESTful APIs in a typical Spring-based application.

It has various flexible options that can abstract most of the tiny details around making HTTP Calls and focus instead of the business logic.

The code for this post is available on Github for reference.


Saurabh Dashora

Saurabh is a Software Architect with over 12 years of experience. He has worked on large-scale distributed systems across various domains and organizations. He is also a passionate Technical Writer and loves sharing knowledge in the community.

0 Comments

Leave a Reply

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