Spring Boot – Calling REST Services with RestTemplate


In this article, we’ll learn how to consume REST services with RestTemplate from a Spring Boot application. Spring provides a RestTemplate class that is used to communicate between two different applications or microservices.

Similar Post: Spring Boot– Consuming a REST Services with WebClient

What we’ll build

We’ll create a Spring Boot application that consumes the data by calling exposed API of another application/microservices. For demonstration, we are using JSON placeholder service which returns some user’s information (treat this JSON mock API as another application).

Mock API: https://jsonplaceholder.typicode.com/users/4

and the response of the API is:

{
  "id": 4,
  "name": "Patricia Lebsack",
  "username": "Karianne",
  "email": "[email protected]",
  "address": {
    "street": "Hoeger Mall",
    "suite": "Apt. 692",
    "city": "South Elvis",
    "zipcode": "53919-4257",
    "geo": {
      "lat": "29.4572",
      "lng": "-164.2990"
    }
  },
  "phone": "493-170-9623 x156",
  "website": "kale.biz",
  "company": {
    "name": "Robel-Corkery",
    "catchPhrase": "Multi-tiered zero tolerance productivity",
    "bs": "transition cutting-edge web services"
  }
}

Dependencies Required

To make it work, make sure these following dependencies are available in your build path. Add the following to your pom.xml.

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

Now the first step is you need to create a domain class to contain the data that you need. For example, User class is the parent class of Address and Company are its child classes and so on.

User.java
package org.websparrow.dto;

public class User {

	private Integer id;
	private String username;
	private String email;
	private Address address;
	private String phone;
	private String website;
	private Company company;
	
	// Generate Getters and Setters...
}
Address.java
package org.websparrow.dto;

public class Address {

	private String street;
	private String suite;
	private String city;
	private String zipcode;
	private Geo geo;
	
	// Generate Getters and Setters...
}
Company.java
package org.websparrow.dto;

public class Company {

	private String name;
	private String catchPhrase;
	private String bs;

	// Generate Getters and Setters...
}

Configuration Class

Create the bean of RestTemplate class by instantiating the RestTemplateBuilder class object.

AppConfig.java
package org.websparrow.config;

import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class AppConfig {

	@Bean
	public RestTemplate restTemplate(RestTemplateBuilder builder) {
		return builder.build();
	}
}

Controller Class

MyController class is used to make a REST call of the exposed API by another application and return an appropriate response to the end-user. In this class, we’ll also autowired the RestTemplate.

1. For Single Object

1. 1 If the API returns a single object in the response:

@GetMapping("/users/single")
public User consumeUser() {
	String url = USER_API + "/2";
	return restTemplate.getForObject(url, User.class);
}

1. 2 If the API returns a single object in the response but required some dynamic parameters:

@GetMapping("/users/{id}")
public User consumeUser(@PathVariable Integer id) {
	String url = USER_API + "/{id}";
	return restTemplate.getForObject(url, User.class, id);
}

2. For an Array of Objects

@GetMapping("/users")
public User[] consumeAllUser() {		
	return restTemplate.getForObject(USER_API, User[].class);
}

Let’s see the complete controller class.

MyController.java
package org.websparrow.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.websparrow.dto.User;

@RestController
public class MyController {

	@Autowired
	private RestTemplate restTemplate;

	private final String USER_API = "https://jsonplaceholder.typicode.com/users";

	@GetMapping("/users/{id}")
	public User consumeUser(@PathVariable Integer id) {
		String url = USER_API + "/{id}";
		return restTemplate.getForObject(url, User.class, id);
	}

	@GetMapping("/users")
	public User[] consumeAllUser() {
		return restTemplate.getForObject(USER_API, User[].class);

	}
}

Run it

SpringBootRestTemplateApp.java
package org.websparrow;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootRestTemplateApp {

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

Test it

Let’s test the application.  To test the application open the Postman and follow the below steps:

Endpoint: http://localhost:8080/users/10

HTTP method: GET

Result: It will make a REST call to an external API and map all the data to our DTO.

{
  "id": 10,
  "name": "Clementina DuBuque",
  "username": "Moriah.Stanton",
  "email": "[email protected]",
  "address": {
    "street": "Kattie Turnpike",
    "suite": "Suite 198",
    "city": "Lebsackbury",
    "zipcode": "31428-2261",
    "geo": {
      "lat": "-38.2386",
      "lng": "57.2232"
    }
  },
  "phone": "024-648-3804",
  "website": "ambrose.net",
  "company": {
    "name": "Hoeger LLC",
    "catchPhrase": "Centralized empowering task-force",
    "bs": "target end-to-end models"
  }
}

Similarly, you can also try http://localhost:8080/users endpoint which returns the array of objects.

References

  1. Spring Boot – TestTemplate
  2. JSONPlaceholder

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.