Spring boot - consume REST API

Thu, Dec 12, 2019

Read in 3 minutes

In this article, we will see how to consume a rest API with spring boot.

Table of content :

  • Introduction
  • Steps to consume a REST API
  • Possible Exceptions and problems
  • Conclusion

Introduction :

We are going to consume this restful service https://reqres.in/api/product. This dummy API is developed for the developers for testing purposes.

This service response is,

Service Response

Steps to consume a rest API :

  • Create POJO class as per the response data.
  • Initiate RestTemplate.
  • Explore RestTemplate methods to consume a Restful service and use a proper method.
  • Test the project.

1. To create the POJO classes, the response data has properties like page,per_page, total and data. So I am going to create two POJO classes named Product and Data.

package com.example.demo.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Data {
 String id;
 String name;
 String year;
 String color;
 String pantone_value;
 public String getId() {
 return id;
 }
 public void setId(String id) {
 this.id = id;
 }
 public String getName() {
 return name;
 }
 public void setName(String name) {
 this.name = name;
 }
 public String getYear() {
 return year;
 }
 public void setYear(String year) {
 this.year = year;
 }
 public String getColor() {
 return color;
 }
 public void setColor(String color) {
 this.color = color;
 }
 public String getPantone_value() {
 return pantone_value;
 }
 public void setPantone_value(String pantone_value) {
 this.pantone_value = pantone_value;
 }
}
package com.example.demo.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Product {
	int page;
	int total;
	Data data[];
	public int getPage() {
		return page;
	}
	public void setPage(int page) {
		this.page = page;
	}
	public int getTotal() {
		return total;
	}
	public void setTotal(int total) {
		this.total = total;
	}
	public Data[] getData() {
		return data;
	}
	public void setData(Data[] data) {
		this.data = data;
	}
}

2. Initiate RestTemplate:

@Autowired
RestTemplate restTemplate;

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

3. Explore RestTemplate methods to consume a Restful service and use a proper method:

RestTemplate is a spring boot central class that has many methods to support web services operations like – “GET, POST,PUT,DELETE”.Here we are using a service which has a “GET ” operation.

@GetMapping("/getProducts")
	public Product getProductDetails() {
		HttpHeaders headers = new HttpHeaders();
		headers.add("user-agent", "Application");
		HttpEntity<String> entity = new HttpEntity<>(headers);
		log.info("endpoint "+endpoint);
		Product productFound = restTemplate
				.exchange(endpoint, HttpMethod.GET, entity, Product.class).getBody();
		return productFound;
	}

Final Code: ProductRestController.java

@RestController
public class ProductRestController {
	private static final Logger log = LoggerFactory.getLogger(ProductRestController.class);
	@Value("${endpoint}")
	String endpoint;
	@Autowired
	RestTemplate restTemplate;
	@Bean
	public RestTemplate restTemplate(RestTemplateBuilder builder) {
		return builder.build();
	}
	@GetMapping("/getProducts")
	public Product getProductDetails() {
		HttpHeaders headers = new HttpHeaders();
		headers.add("user-agent", "Application");
		HttpEntity<String> entity = new HttpEntity<>(headers);
		log.info("endpoint " + endpoint);
		Product productFound = restTemplate.exchange(endpoint, HttpMethod.GET, entity, Product.class).getBody();
		return productFound;
	}
}

Finally, test your code by hitting (http://localhost:8080/getProducts) and you should the below output

code output

Possible Exceptions and problems

403 Forbidden: [error code: 1010]: If you didn’t add user agent in header you may get this 403 error.

headers.add(“user-agent”, “Application”);

com.fasterxml.jackson.databind.exc.MismatchedInputException: If you didn’t specify the data type properly in POJO, you will get this error. In this example you didn’t declare data’s type as an array , you will get Exception.

Data data[];