Spring RestTemplate Example

Sometimes we need to Access a third-party REST service inside a Spring application or other standalone applications. For that, we need to use the Spring RestTemplate class.

RestTemplate class contains all required HTTP methods to call web services. An internally rest template uses java servlet API. It is a Synchronous client to perform HTTP requests, exposing a simple, template method API over underlying HTTP client libraries such as the JDK HttpURLConnection, Apache HttpComponents, and others.


RestTemplate has many Methods

we will see two methods with examples

 Http Method Modifier and Type Method and Description
 GET  <T> TgetForEntity(String url, Class<T> responseType, Object... uriVariables) Retrieve an entity by doing a GET on the specified URL.
 POST <T> T postForEntity(URI url, Object request, Class<T> responseType)

The RestTemplate offers templates for common scenarios by the HTTP method, in addition to the generalized exchange and execution methods that support of less frequent cases.

Here we see how to use restTemplate for standalone java application.

Here we tested code by writing the JUnit test cases.

We need 2 dependencies spring framework web and JUnit test

 
 <dependency>
 <groupid>org.springframework</groupid>
<artifactid>spring-web</artifactid>
<version>5.2.6.RELEASE </version>
 </dependency>
 
 <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13</version>
    <scope>test</scope>
</dependency>

We assume that we have a Student Pojo Class As

 
class Student
{ 
private int id;
private String firstName; 
private String lastName;
private String rollNumber 
}
//@Getter @Setter @ToString
}

We have Example here


public class RestTemplateExample {

private static final Logger logger = LoggerFactory
.getLogger(RestTemplatePostFile.class);

ObjectMapper mapper = new ObjectMapper();

public static Student getData(int id)
{
 ResponseEntity<Employee> entity = restTemplate.getForEntity(REQUEST_URI + "/{id}",
 Employee.class, Long.toString(id)); 
LOG.info("Status code value: " + entity.getStatusCodeValue());
 LOG.info("HTTP Header 'ContentType': " + entity.getHeaders().getContentType());
//convert reponse to Student compatible
 return entity;
}

public static ResponseEntity<String> postData(String url,
HttpHeaders headers, Student student) throws IOException, ApiError {
ResponseEntity<String> response = null;
RestTemplate restTemplate = new RestTemplate();
 
 
//also we converting our json data to string to send to the web service
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("content", eStr.toString());

//here we set http headers reqyuired by other web service
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(
map, headers);

HttpEntity<String> entity = new HttpEntity<String>(headers);

try {
response = restTemplate.postForEntity(url, request, String.class);

} catch (Exception ex) {
Map<String, String> errors = new HashMap<String, String>();
logger.info("Error occured duting posting the file to api gateway:"
+ ex.getMessage());

}

logger.info("body: " + response.getBody());
logger.info("statusCode: " + response.getStatusCode());
logger.info("statusCodeValue: " + response.getStatusCodeValue());
return response;
}

Test Post API call

 
@Test
public void testPostData() throws IOException, ApiError {

HttpHeaders headers = new HttpHeaders();
headers.add("content-type", "application/json");

Student student = new  Student ();
student.setId(1);
student.setFirstName("Bala");
student.setRoleNumber("A00001");
RestTemplateExample.postFile("your web service url here", headers, student);
logger.info("post data using resTemplate done!!!");
}

Test get API call

 
@Test
public void testgetData() throws IOException, ApiError {

 Student student = RestTemplateExample.getData("http://www.mocky.io/v2/5ed7daa5320000b31b274cdf");
 logger.info("Student First Name is: {}", student.getFirstName());
 logger.info("Student Last Name is: {}", student.getLastName()); 
 logger.info("Student  RoleNumber is: {}", student.getRoleNumber()); 
 
} 
  

In this article, we have seen how we can use RestTemplate.in other application Applications or standalone applications.

For full source code please check our GitHub Repository.