Consuming a RESTful Webservice – Part IV

Continuing the series of posts on Spring Boot, in this post, we will investigate how to consume a REST API service we built previously. This will be a short post on how to use Rest Template to call REST service. We will show how to read the data and how to post the data with some of the features Spring Boot offers to consume a REST service for the client-side.

The eventual goal is to use this feature to call our rest service during runtime to use the data from the database to display on views that a user will be able to see.

You can read previous posts on this series Part I, Part II, and Part III.

Purpose

The purpose of this post is to read company data from Company REST API and also to create a company by posting company data using the same REST API.

Build a client with Rest Template

To consume a rest service programmatically, Spring provides a feature called RestTemplate. RestTemplate is the easiest way for a client to interact with the server-side code with just one line of code.

In our client code, we will need a RestTemplate object, REST service URL. Since this is a sample we are building, we will be adding the main method in this class to run this client side of the code. In real-life scenarios, during runtime, client code will call the rest template to get server-side data, and use that data to massage or display to the user on the user interface.

 

RestTemplate restTemplate = new RestTemplate();
String resourceAPI_URL = "http://localhost:8080/benefits/v1/companies/{id}";
Company company = restTemplate.getForObject(resourceAPI_URL, Company.class, 1);

This code is showing that we are calling REST service to read company data for a company with id that a client will pass.

Similarly, we will have another request to post the data on the server side to create a company. The code for that will look like below:

String resourceAPI_POSTURL = "http://localhost:8080/benefits/v1/companies/";

Company comp = new Company();

comp.setName("XYZ Company");
comp.setStatusid(1);
comp.setType("Corporation");
comp.setEin("9343423232");

Company newcomp = restTemplate.postForObject(resourceAPI_POSTURL, comp, Company.class);

In this post, we showed how to use RestTemplate a feature that Spring Boot provides to consume a REST service. The code for this is available here

Home » Java » Consuming a RESTful Webservice – Part IV

 

One thought on “Consuming a RESTful Webservice – Part IV

  1. Pingback: Producing and Consuming SOAP Webservice with Spring Boot – Part V | Code Junkie

Comments are closed.