There are many ways to implement Rest client in SpringBoot however RestTemplate is definitely a simple and clear approach. In a nustshell, the RestTemplate is a Rest client offered by Spring’s spring-web module which provides methods to “consume” rest data. Let’s see a practical example of it:
We will start from the following sample Controller class which has both a GET and a POST method to manage a list of Customer objects:
package com.example.testrest;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
@RestController
public class CustomerController {
@Autowired CustomerRepository repository;
@GetMapping("/list")
public List<Customer> findAll() {
return repository.getData();
}
@PostMapping(path = "/save", consumes = MediaType.APPLICATION_JSON_VALUE)
public void save(@RequestBody Customer customer) {
System.out.println("got " + customer);
repository.save(customer);
System.out.println("Saved customer");
}
}
The Repository class is pretty trivial, as it merely stores the Customer object in a List:
package com.example.testrest;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
@Component
public class CustomerRepository {
List<Customer> customerList = new ArrayList<Customer>();
@PostConstruct
public void init() {}
public List<Customer> getData() {
return customerList;
}
public void save(Customer c) {
customerList.add(c);
}
}
The Customer class is a POJO:
package com.example.testrest;
public class Customer {
private int id;
private String name;
public Customer(int id, String name) {
super();
this.id = id;
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
Now for the RestTemplate Here is an Application class which implements the CommandLineRunner to execute some actions after the application has started:
package com.example.testrest;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.boot.CommandLineRunner;
import java.util.Arrays;
@SpringBootApplication public class DemoApplication implements CommandLineRunner {
@Bean public RestTemplate getRestTemplate() {
return new RestTemplate();
}
public void saveCustomer(Customer customer) {
HttpHeaders headers = new HttpHeaders();
headers.add("Accept", MediaType.APPLICATION_JSON_VALUE);
headers.setContentType(MediaType.APPLICATION_JSON);
RestTemplate restTemplate = new RestTemplate();
// Data attached to the request.
HttpEntity < Customer > requestBody = new HttpEntity < > (customer, headers);
// Send request with POST method.
restTemplate.postForObject("http://localhost:8080/save", requestBody, Customer.class);
}
public void listCustomers() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity < String > entity = new HttpEntity < String > (headers);
ResponseEntity < Customer[] > response = getRestTemplate().exchange("http://localhost:8080/list", HttpMethod.GET, entity, Customer[].class);
HttpStatus statusCode = response.getStatusCode();
System.out.println("Response Status Code: " + statusCode);
// Status Code: 200
if (statusCode == HttpStatus.OK) {
// Response Body Data
Customer[] list = response.getBody();
if (list != null) {
for (Customer c: list) {
System.out.println(c.toString());
}
}
}
}
public void run(String...args) {
Customer c1 = new Customer(1, "john");
Customer c2 = new Customer(2, "frank");
saveCustomer(c1);
saveCustomer(c2);
listCustomers();
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Let’s see more in detail how RestTemplate works.
The RestTemplate is injected as a Bean in the Application class:
@Bean public RestTemplate getRestTemplate() {
return new RestTemplate();
}
Then, the method saveCustomer uses the postForObject method of the RestTemplate to invoke the “/save” URI, passing as argument a Customer in the HttpHeaders:
restTemplate.postForObject("http://localhost:8080/save", requestBody, Customer.class);
Much the same way, the listCustomers method uses the getRestTemplate().exchange to invoke the GET method “/list” and retrieve an array of Customer object:
ResponseEntity < Customer[] > response = getRestTemplate().exchange("http://localhost:8080/list", HttpMethod.GET, entity, Customer[].class);
In order to compile this project, the minimal requirement is to include in your pom.xml:
<?xml version="1.0" encoding="UTF-8"?><project>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</project>
Source code for this RestTemplate example: https://github.com/fmarchioni/masterspringboot/tree/master/rest/demo-rest-template
Found the article helpful? if so please follow us on Socials