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, but 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 client side. Eventual goal is to use this feature to call our rest service during runtime to use the data from database to display on views which a user will be able to see.

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

Purpose

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

To consume a rest service programmatically, Spring provides a feature called RestTemplate. RestTemplate is easiest way for client to interact with 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 a main method in this class to run this client side of the code. In real life scenarios, during runtime, a client code will call rest template to get server side data, use that data to massage or display to user on 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 company with id that a client will pass.

Similarly, we will have another request to post the data on 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");
// comp.setCp(cp);
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

Advertisements

One thought on “Consuming a RESTful Webservice – Part IV

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s