How to consume REST based web service in Spring BOOT - Little Big Extra Skip to main content

How to consume REST based web service in Spring BOOT

How to consume REST based web service in Spring BOOT


In my last tutorial I wrote about Consuming a secure SOAP based web service in Spring Boot application, In this tutorial, I will talk about consuming a simple unsecured REST service in Spring Boot
Consuming REST service is very simple and less ad-hoc than SOAP service

Create a REST Template Bean

RestTemplate is spring’s central class for synchronous client side HTTP access.It enforces REST principles and simplifies communication by handlings HTTP connections leaving application code to provide URLs and extract results.
In our code, we will create a bean where we will instantiate a new RestTemplate


Now we have rest template instance we can use the RestTemplate methods to call web service

Consuming a service by HTTP GET method

You can use Rest Template getForObject or getForEntity methods to make an HTTP GET call. Both of these operations need a URL and the ResponseObject class.
A simple example would be like below.


Consuming a service by HTTP POST method

Consuming a service by POST means that we will be sending some information over HTTP to the requested service and that service based on will request will process things at its end like updating a DB, recording a transaction or something similar and will give us the result back.

In Post also we can use Response Template postForObject and postForEntity Method to send a request

Using postForObject

In below example, we are using an HTTP GET @GetMapping(“/Availability”) method which can be directly called by a  browser using a URL like http://localhost:8080/Availability. In this method, we will call the postForObject method and pass the endpoint URL of the service, the request object it needs and the Response type we expect.


Using postForEntity

Method post for Entity can be used exactly as shown above, however, the return type is ResponseEntity which represents entire HTTP Response, it has HTTP response like 200,404 etc and response body.

In the below method we have to use a REST CLIENT ( like Chrome plugins Postman or AdvancedRestClient) and directly post the JSON request. @RequestBody will automatically map the JSON object to Request object, there is no need to map any elements or create a new request object.

Here is how the complete code looks like

Add the URL in application.yml YAML/properties file


Maven Dependencies

Following dependencies were enough for above example to work




Related Posts

2 thoughts to “How to consume REST based web service in Spring BOOT”

Leave a Reply

Your email address will not be published. Required fields are marked *