Tuesday, June 08, 2021

How to consume RESTful service (REST API) in Spring Boot.

springboot,java,autowired,requestmapping,restcontroller,programming,software development,technology
Spring Boot is used to create RESTful APIs. At the same time, we can use RestTemplate to consume RESTful services, such as payment services or weather services, in Spring Boot.

Public REST API

We will use a public RESTful service in this tutorial. Numerous websites offer public RESTful services. https://reqres.in/ has some useful RESTful services. It includes the GET, POST, PUT, PATCH, and DELETE rest APIs.

We use a RESTful service, which is accessible at https://reqres.in/api/users?page=1. I used a web browser to call this service, and it returned a list of dummy user details in JSON format, as shown below:
{ 
  "page":1, 
  "per_page":6, 
  "total":12, 
  "total_pages":2,
  "data":[
  	{"id":1,"email":"george.bluth@reqres.in","first_name":"George",
    	"last_name":"Bluth","avatar":"https://reqres.in/img/faces/1-image.jpg"},
  	{"id":2,"email":"janet.weaver@reqres.in","first_name":"Janet",
    	"last_name":"Weaver","avatar":"https://reqres.in/img/faces/2-image.jpg"},
  	{"id":3,"email":"emma.wong@reqres.in","first_name":"Emma",
    	"last_name":"Wong","avatar":"https://reqres.in/img/faces/3-image.jpg"},
  	{"id":4,"email":"eve.holt@reqres.in","first_name":"Eve",
    	"last_name":"Holt","avatar":"https://reqres.in/img/faces/4-image.jpg"},
  	{"id":5,"email":"charles.morris@reqres.in","first_name":"Charles",
    	"last_name":"Morris","avatar":"https://reqres.in/img/faces/5-image.jpg"},
  	{"id":6,"email":"tracey.ramos@reqres.in","first_name":"Tracey",
    	"last_name":"Ramos","avatar":"https://reqres.in/img/faces/6-image.jpg"}
  ], 
  "support": { 
  	"url":"https://reqres.in/#support-heading", 
  	"text":"To keep ReqRes free, contributions towards server costs are appreciated!" 
  	} 
}

Use of RestTemplate

RestTemplate is a very useful class provided by Spring. We can communicate with RESTful services by using RestTemplate.

You must first create a Spring Boot application. Spring Initializr can be used to create a Spring Boot application, and your project must include the Spring Web dependency. Simply download the zip file, unzip it in your desired location, and import the project into your preferred IDE.

If you look closely at the JSON document, you'll notice that it requires three classes to hold the data - a main class and two sub-classes to support the main class. The main class is responsible for capturing the entire JSON document data, and there are two sub-classes for data (actually user details) and support.

So, for the Data class, write the following code:
package com.example.springresttemplate;

public class DataClass {                
	private int id;
	private String email;
	private String first_name;
	private String last_name;
	private String avatar;

	public int getId() { return id;}
	public void setId(int id) { this.id = id; }

	public String getEmail() { return email; }
	public void setEmail(String email) { this.email = email; }

	public String getFirst_name() { return first_name; }
	public void setFirst_name(String first_name) { this.first_name = first_name; }

	public String getLast_name() { return last_name; }
	public void setLast_name(String last_name) { this.last_name = last_name; }

	public String getAvatar() { return avatar; }
	public void setAvatar(String avatar) { this.avatar = avatar; }

	@Override
	public String toString() { 
	  return "DataClass [id=" + id + ", email=" + email + ", first_name=" +
		 first_name + ", last_name=" + last_name + ", avatar=" + avatar + "]"; 
	}
}

Now, for the Support class, write the following code:
package com.example.springresttemplate;

public class SupportClass {
	private String url;
	private String text;

	public String getUrl() { return url; }
	public void setUrl(String url) { this.url = url; }
	public String getText() { return text; }
	public void setText(String text) { this.text = text; }

	@Override
	public String toString() { return "SupportClass [url=" + url + ", text=" + text + "]"; }
}

Finally, here is a listing for the Main class:
package com.example.springresttemplate;
import java.util.Arrays;
            
public class MainClass {
	private int page;
	private int per_page;
	private int total;
	private int total_pages;
	private DataClass[] data;
	private SupportClass support;

	public int getPage() { return page; }
	public void setPage(int page) { this.page = page; }

	public int getPer_page() { return per_page; }
	public void setPer_page(int per_page) { this.per_page = per_page; }

	public int getTotal() { return total; }
	public void setTotal(int total) { this.total = total; }

	public int getTotal_pages() { return total_pages; }
	public void setTotal_pages(int total_pages) { this.total_pages = total_pages; }

	public DataClass[] getData() { return data; }
	public void setData(DataClass[] data) { this.data = data; }

	public SupportClass getSupport() { return support; }
	public void setSupport(SupportClass support) { this.support = support; }

	@Override
	public String toString() {
	  return "MainClass [page=" + page + ", per_page=" + per_page + ", total=" +
		total + ", total_pages=" + total_pages + ", data=" + Arrays.toString(data) +
		  ", support=" + support + "]";
	}
}

Now, in the controller class RestFulController, we create a web request method, as shown in the code below:
package com.example.springresttemplate;
// imports are removed
            
@RestController
@RequestMapping("/restful")
public class RestFulController {    
	private static final Logger LOGGER = Logger.getLogger(RestFulController.class);

	@Autowired
	RestTemplate restTemplate;

	@RequestMapping(value = "/users", method = RequestMethod.GET)
	public void getUsers(HttpServletRequest request) {
		MainClass mainClass = this.restTemplate.getForObject("https://reqres.in/api/users?page=1", 
								MainClass.class);
		LOGGER.info("Response -> " + mainClass.toString());
	}
}

We've used RestTemplate to create a simple GET web request method for interacting with a RESTful service. We called a RESTful service using the getForObject() method, which retrieves the data and stores it in MainClass before logging the result to the console.

Now, open any browser and navigate to this URL: http://localhost:8080/restful/users, then return to your IDE and open the console. The end result is shown below:
2021-06-08 09:56:03 INFO RestFulController:24 - Response -> MainClass
[
	page=1, per_page=6, total=12, total_pages=2, 
	data=[DataClass [id=1,email=george.bluth@reqres.in, first_name=George, last_name=Bluth, 
		avatar=https://reqres.in/img/faces/1-image.jpg], 
	DataClass [id=2, email=janet.weaver@reqres.in, first_name=Janet, last_name=Weaver, 
		avatar=https://reqres.in/img/faces/2-image.jpg], 
	DataClass [id=3, email=emma.wong@reqres.in, first_name=Emma, last_name=Wong, 
		avatar=https://reqres.in/img/faces/3-image.jpg], 
	DataClass [id=4, email=eve.holt@reqres.in, first_name=Eve, last_name=Holt, 
		avatar=https://reqres.in/img/faces/4-image.jpg], 
	DataClass [id=5, email=charles.morris@reqres.in, first_name=Charles, last_name=Morris, 
		avatar=https://reqres.in/img/faces/5-image.jpg], 
	DataClass [id=6, email=tracey.ramos@reqres.in, first_name=Tracey, last_name=Ramos, 
		avatar=https://reqres.in/img/faces/6-image.jpg]], 
	support=SupportClass[url=https://reqres.in/#support-heading, 
	text=To keep ReqRes free, contributions towards server costs are appreciated!]
]

In this manner, we can use RestTemplate in Spring to call RESTful services.
I'll write a tutorial on how to POST/PUT/DELETE RESTful services using RestTemplate later.
in

1 comment:

Popular posts