Updated April 7, 2023
Definition of Spring Boot RestTemplate
In Spring boot we can make use of RestTemplate which helps us to invoke the PAI from the application itself, we can write method which invoke the API from it to consume the data and for further processing. RestTemplate is present inside the started-web dependency of spring boot. If we want to use it we can simply auto wired its object and use its different methods available to make any type of request from the application. By the use of it we can perform get, post, put, delete any request. But from spring boot newer version it is going to deprecate soon, and they have come up with webclient to use as an alternative for this. But in this tutorial we will see how to implement RestTemplate and make use of it, to invoke the APIS for better understating of the implementation for beginners.
Syntax:
As we know that it is a mechanism we can say to call the HTTP endpoints using the RestTemplate, by making some small configurations and few lines of code. Let’s take a closer look at the syntax for better understating of its usage see below;
@Autowired
private RestTemplate name_of_variable;
As you can see in the above syntax we make this line of code to use the RestTemplate inside the program to invoke any URL. Let’s take an closer look at the practice syntax for better understating, see below;
Example:
public class Test{
@Autowired
private RestTemplate restTemplate;
}
In this way we can use this RestTemplate inside the spring boot class, in the coming section of the tutorial we will see more details configuration which is required to make this work, also how to invoke the API using RestTemplate in our application.
How Spring Boot RestTemplate Works?
As we already know that when to use RestTemplate in our application , suppose we have one scenario where i want to gather the data from third API or we can say my application which s running on differ server, so in order to get the data from differ server we would require to have make an HTTP request toward that server, once we make the request it will return us the data we want, also we should be aware about the URL we want to hit from our application. So in such scenario where we have to make HTTP request in order to get or send the data we can use RestTemplate, we should also know the method type because while writing code for restTemplate we have to use appreciate methods to invoke the API and have to pass all the required parameters as well as part of the URL only. In this section we will first see the required configuration that we have to make in order to run this application let’s get started;
- Web Dependency: To make use of resttemplate we have to use this web dependency because it contain the required packages for this. So while creating the application or project add this dependency also.
- Auto Wiring: After this we have to auto-wire the RestTemplate object inside our program where we want to make an RestTemplate call toward an URL. this is very normal and simple like we do for other component and services, we have application. So spring container now will take care of all the dependency for us, we do not need to make this explicitly.
- Method: we can make one method inside which we can write the logic to use Rest Template to call the endpoint. It has so many different method to make the different type of call, let’s take an closer look at each of them in detail see below;
- First we have to auto wire the RestTemplate object inside the class we want to make use of RestTemplate, after this we can use the below method to call the API,
Example:
final HttpEntity<String> request = new HttpEntity<>(json.toString(), your_headers);
ResponseEntity<String> response = this.restTemplate.exchange(your_URL, HttpMethod.POST, your-REQUEST, class_type.class);
As you can see i the above code we are making use of exchange method here, but it takes many parameters as the input here. We can also pass the headers inside it, to validate the URL at other side. Let’s first discuss the parameters t take;
- URL: it specify the URL or API endpoint we want to hit from our application to get or post the data depended on the requirement.
- Method Type: second parameter here specify the type of the Method it is.
- request : third parameters is the request means the HttpEntity object which contain the parameters of URL or headers.
- Class Type: Last parameters specify the type of response it will return.
Examples
In this example we are just writing the rest template method to get the data response from the URL we have. You can replace the parameters with your, and try to hit the method by using test class or any advanced rest client. Everything should be in place to run this.
Code:
import com.scania.coc.core.common.handler.RestTemplateResponseErrorHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class RestTemplateDemo {
private static final Logger logger = LoggerFactory.getLogger(RestTemplateDemo.class);
@Autowired
private String postEntity(String url, JSONObject json) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
final HttpEntity<String> request = new HttpEntity<>(json.toString(), headers);
ResponseEntity<String> response = this.restTemplate.exchange(url, HttpMethod.GET, request, String.class);
if (response.getStatusCode().equals(HttpStatus.OK)) {
System.out.println("got response succsessfully");
}
return "";
}
}
- Main class should be like below;
Code:
@SpringBootApplication
@EnableScheduling
@EnableJpaRepositories
public class TestApplication{
public static void main(String[] args) throws JsonProcessingException {
SpringApplication.run(TestApplication.class, args);
}
}
- run application it should run without any error;
Output:
Conclusion
By the use of RestTemplate we are able to invoke the API from our application, also we can get data from third party or other application if we have any dependency. So basically it is used to make the REST call to the application. These are very easy to use and handle by the developers as well without less configuration needed.
Recommended Articles
This is a guide to Spring Boot RestTemplate. Here we also discuss the introduction and key points on qualify along with examples. You may also have a look at the following articles to learn more –