Spring boot RestTemplate example

The AWS CloudWatch Logs Agent can be set up to push logs to the AWS CloudWatch.It's not mandatory to you that you should have an ec2 instance. You can set up it on any server like AWS, Linode, DigitalOcean, Google, Azure, etc.

RestTemplate is also a high-level API, which in turn is based on an HTTP client. By default, the class java.net.HttpURLConnection from the Java SDK is used in RestTemplate. However, the Spring Framework makes it possible to easily switch to another HTTP client API.

Using RestTemplate we call web service endpoint and bind the response according to our requirements

For Restemplate we need the following things.

1) A maven project or We can use the spring initializer where we can download the project with a predefined structure and where we can add all the required dependencies. 

 Go to Spring Initializr

  • Select maven project
  • Then select spring boot version we have latest 2.3.0
  • Select or put values for
  • groupId -> com.bala.sprinng.boot.rest.template
  • artifactId -> spring-boot-rest-template-example
  • Package Name  -> com.bala.sprinng.boot.rest.template 
  • Packaging  -> Jar
  • Java -> 8

Press Control + or download.

spring-boot-rest-template-example.jpg


Extract the zip file. Go to project dir and open cmd for that location.

If converting our project to eclipse project and downloading the maven dependencies. If you don't have java installed here it is Install Oracle java8

If you don't have maven installed then here is a tutorial for it.

Open project root dir.i.e where the pom.xml is present. then use following commands

 
   
mvn eclipse:clean

mvn eclipse:eclipse

mvn clean install
 

If we have no error while making build.then We can import project in eclipse. Import project in the eclipse. Then

We need to create the following :

 1). A POJO class where we call web service call using Http method for various operations like

POST Update Delete Patch Get

 2).  Maven dependencies if not included. 

 3). RestTemplate Configuration class

 

 <dependency>
 <groupid>org.springframework.boot</groupid>
 <artifactid>spring-boot-starter-web</artifactid>
 </dependency> 

<dependency>
 <groupid>org.apache.httpcomponents</groupid> 
 <artifactid>httpclient</artifactid> 
</dependency>

 <dependency> 
<groupid>org.projectlombok</groupid>
 <artifactid>lombok</artifactid> 
<optional>true</optional>
</dependency> 

 

Here is POJO.

In POJO we use Lombok If you have a problem while setting Lombok in the eclipse. Please follow the Configure Lombok in eclipse

 

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

If you still have a problem with setting the Lombok. 

 Please remove Lombok dependency from pom.xml @Getter @Setter @ToString in this POJO

then,

Generate It manually using eclipse: 

Project->Source->Generate Getter and Setter 

 Project->Source-> GenerateToString

Then we have configuration class

 

@Configuration
@Component
class MyAppConfiguration {

@Bean
public RestTemplate restTemplate()
{
RestTemplate template = new RestTemplate();

//template.set
return template
}

  @Bean  
public ObjectMapper mapper()
{
  ObjectMapper objectMapper  = new  ObjectMapper ();
//  objectMapper    setting
return  objectMapper;
  
}
 

This class provides over 50 methods, most of them are overloaded several times. The following table gives a rough overview: Method Description void delete Executes a DELETE request and returns nothing.


1). T getForObject 

 Works similar to getForEntity, but returns the resource directly. HTTP headers headForHeaders Executes a HEAD request and returns all HTTP headers for the specified URL. Set optionsForAllow Executes an OPTIONS request and uses the Allow header to return which HTTP methods are allowed under the specified URL.

2). T patchForObject 

 Executes a PATCH request and returns the representation of the resource from the response. The JDK HttpURLConnection does not support PATCH, but Apache HttpComponents and others do.

3). ResponseEntity postForEntity

 Executes a POST request and returns a ResponseEntity which contains the status code as well as the resource as an object. URI postForLocation Works like postForEntity but returns the Location header from the response, which indicates under which URI the newly created resource can be reached.

4). T postForObject 

Works like postForEntity but returns the resource directly. void put Executes a PUT request and returns nothing.

5). ResponseEntity exchange 

Executes a specified HTTP method, such as GET or POST, and returns a ResponseEntity that contains both the HTTP status code and the resource as an object.

6). T execute

 Works similar to exchange, but expects an additional RequestCallback and a ResultSetExtractor as parameters. This is useful, for example, if you frequently create complex requests or want to process complex responses.

7) ResponseEntity getForEntity Executes a GET

 request and returns a ResponseEntity that contains both the status code and the resource as an object.

Now We have a controller class 

 1). getForObject()

 
@RestController
class MainController
{

@Value("apiUrl")
private String endPoint;
//this is only live api response from mocky.io , for other you have to set or host web service for reponse.

@GetMapping("/get/{studentId}")
public Student getStudent(in studentId)
{
String formattedendPint = String.format(enpoint,id);
Student jsonString = restTemplate.getForObject( formattedendPint , Student.class, id);
}
 

DO you see the template internally uses object mapper which we configured in MyAppConfigurationClass?

Then we have

2). postForObject()

 
@PostMapping
public Student postForObject(Student newStudent)
 {
 return restTemplate.postForObject( endPoint , newStudent, Student.class);
}
 

3). PUT 

The method put() is used for an HTTP PUT.

This method return void. We can use this method to update the student:

 
  @PutMapping("")  
public void put(Student student )
 {
 restTemplate.put(REQUEST_URI + "/{id}", updatedStudent, Long.toString(student.getId()));
}

 

4). Exchange


Sometimes we need ResponseEntity as a response since this gives us HTTP status code and the HTTP headers sent along by the server.we have to exchange

so we have

 
@PutMapping("")
public ResponseEntity putWithExchange(Student updatedStudent)
{
String id =  Long.toString(updatedStudent.getId();
 return restTemplate.exchange( endPoint + "/{id}", HttpMethod.PUT, new HttpEntity<>(updatedStudent), Student.class, id ));
}
 

5). HEAD

HTTP headers of an HTTP request are of interest, we use method headForHeaders():

     
public HttpHeaders headForHeaders()
 {
 return restTemplate.headForHeaders(endPoint );
}
 

5). DELETE

this is used to delete student

   
public void delete(long id)

 {
 restTemplate.delete(endPoint + "/{id}", Long.toString(id));
}  

For HTTP status code or the HTTP headers are of interest, the method exchange() must be used:

 
 public ResponseEntity deleteWithExchange(long id)
 {
      String stringId =  Long.toString(id) ;

     return restTemplate.exchange( endPoint + "/{id}", HttpMethod.DELETE, null, Void.class, stringId );
}  

we can send our own values in the HTTP header to the server. which returns a ResponseEntity

 
public ResponseEntity postForEntity(Student newStudent) 
{
    MultiValueMap headers = new HttpHeaders(); 
    headers.add("User-Agent", "StudentRestClient demo class"); 
    headers.add("Accept-Language", "en-US");

    HttpEntity entity = new HttpEntity<>(newStudent, headers); 
    return restTemplate.postForEntity( endPoint , entity, Student.class);

}


  

In this article, we have seen how we use RestTemplate in Spring boot Application. Also, we have seen its methods numerous code examples for the following HTTP Methods: GET POST PUT DELETE HEAD OPTIONS.

For full source code please check our GitHub Repository.