Spring RESTful Client using RestTemplate

Introduction

There are scenarios where we might need to create a RESTful client within our Spring application to access a Third Party REST service. We can do this with the help of the RestTemplate class provided by Spring Framework.

In this tutorial, we will create a short demo on using RestTemplate and log Third Party REST service call response in our server console.

Implementation

Assuming that we have a ready REST Service with us as –


http://localhost:8080/RESTTemplateWithSpring/API/Employee/{employeeName}

In the following demo, what we can do is, call the above REST Service URI from our RESTful Client, while passing appropriate employeeName as path variable, something like –

http://localhost:8080/RESTTemplateWithSpring/API/Employee/Rajesh

Click here to learn how to create a REST Service with Spring

Creating the RESTful Client

Basically, you can create a separate client class and create a method to invoke the REST service and fetch the response as a JSON or as an Object.

Executing the Restful Client

On executing the process method, we see something like below getting logged into the server console –

REST Template console log

If the JSON response needs to be mapped to a POJO, we need to make sure the corresponding POJO is available. For example, if we need to map the JSON response to an Employee POJO, we need to make the REST call as –

Now when the process method is invoked, we see something like below getting logged into the server console –

REST Template console log 2

Download source code

Receive our updates to your inbox

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.