Skip to content
A guide on how to use MicroProfile Rest Client to invoke RESTful microservices over HTTP in a type-safe way: https://openliberty.io/guides/microprofile-rest-client.html
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
finish Multipane (#65) Feb 27, 2019
start Update server.xml Mar 5, 2019
.gitignore
.travis.yml
LICENSE
README.adoc

README.adoc

Consuming RESTful services with template interfaces

Note
This repository contains the guide documentation source. To view the guide in published form, view it on the Open Liberty website.

Learn how to use MicroProfile Rest Client to invoke RESTful microservices over HTTP in a type-safe way.

What you’ll learn

You will learn how to build a MicroProfile Rest Client to access remote RESTful services. You will create a template interface that maps to the remote service that you want to call. MicroProfile Rest Client automatically generates a client instance based on what is defined and annotated in the template interface. Thus, you don’t have to worry about all of the boilerplate code, such as setting up a client class, connecting to the remote server, or invoking the correct URI with the correct parameters.

The application that you will be working with is an inventory service, which fetches and stores the system property information for different hosts. Whenever a request is made to retrieve the system properties of a particular host, the inventory service will create a client to invoke the system service on that host. The system service simulates a remote service in the application.

You will instantiate the client and use it in the inventory service. You can choose from two different approaches, Context and Dependency Injection (CDI) with the help of MicroProfile Config or the RestClientBuilder method. In this guide, you will explore both methods to handle scenarios for providing a valid base URL.

  • When the base URL of the remote service is static and known, define the default base URL in the configuration file. Inject the client with CDI method.

  • When the base URL is not yet known and needs to be determined during the run time, set the base URL as a variable. Build the client with the more verbose RestClientBuilder method.

Try what you’ll build

To try out the application, first navigate to the finish directory, which contains the complete inventory application. Then, run the following Maven goals to build the application and run it inside Open Liberty:

cd finish
mvn install liberty:start-server

After you start the application, you can access the following microservices:

  • The http://localhost:9080/system/properties microservice simulates the remote system service that retrieves the system property information for a specific host. In this case, localhost is a specific host name.

  • The http://localhost:9080/inventory/systems/localhost microservice is the inventory service that invokes the http://localhost:9080/system/properties microservice to retrieves the system property information.

  • The http://localhost:9080/inventory/systems/{your_hostname} microservice is the inventory service that invokes the http://{your_hostname}:9080/system/properties microservice. In Windows, Mac OS, and Linux, get your fully qualified domain name (FQDN) by entering hostname from your terminal. Visit the URL by replacing {your_hostname} with your FQDN. You will see the same system property information, but the process of getting the information is different.

When you are done checking out the application, stop the Open Liberty server. You must stop your running Open Liberty server before you re-install it next time.

mvn liberty:stop-server

Writing the RESTful client interface

Now, navigate to the start directory to begin.

The MicroProfile Rest Client API is added as a dependency to your pom.xml file. Look for the dependency with the mpRestClient artifact ID.

pom.xml

link:finish/pom.xml[]

This dependency provides the library that is required to implement the MicroProfile Rest Client interface.

The mpRestClient feature is also enabled in the src/main/liberty/config/server.xml file. This feature enables your Open Liberty server to use MicroProfile Rest Client to invoke RESTful microservices.

server.xml

link:finish/src/main/liberty/config/server.xml[]

The code for the system service in the src/main/java/io/openliberty/guides/system directory is provided for you. It simulates a remote RESTful service that the inventory service invokes.

Create a RESTful client interface for the system service. Write a template interface that maps the API of the remote system service. The template interface describes the remote service that you want to access. The interface defines the resource to access as a method by mapping its annotations, return type, list of arguments, and exception declarations.

Create the SystemClient class.
src/main/java/io/openliberty/guides/inventory/client/SystemClient.java

SystemClient.java

link:finish/src/main/java/io/openliberty/guides/inventory/client/SystemClient.java[]

The MicroProfile Rest Client feature automatically builds and generates a client implementation based on what is defined in the SystemClient interface. Thus, you don’t waste time on setting up the client and connecting with the remote service.

When the getProperties() method is invoked, the SystemClient instance sends a GET request to the <baseUrl>/properties endpoint.

The @RegisterProvider annotation tells the framework to register the provider classes to be used when the framework invokes the interface. You can add as many providers as necessary. In the SystemClient interface, add a response exception mapper as a provider to map the 404 response code with the UnknownUrlException exception.

Handling exceptions through ResponseExceptionMappers

Error handling is an important step to ensure that the application can fail safely. If there is an error response such as 404 NOT FOUND when invoking the remote service, you need to handle it. First, define an exception, and map the exception with the error response code. Then, register the exception mapper in the client interface.

Look at the client interface again, the @RegisterProvider(UnknownUrlExceptionMapper.class) annotation registers the UnknownUrlExceptionMapper response exception mapper. An exception mapper maps various response codes from the remote service to throwable exceptions.

SystemClient.java

link:finish/src/main/java/io/openliberty/guides/inventory/client/SystemClient.java[]

Implement the actual exception class and the mapper class to see how this mechanism works.

Create the UnknownUrlException class.
src/main/java/io/openliberty/guides/inventory/client/UnknownUrlException.java

UnknownUrlException.java

link:finish/src/main/java/io/openliberty/guides/inventory/client/UnknownUrlException.java[]

Now, link the UnknownUrlException class with the corresponding response code through a ResponseExceptionMapper mapper class.

Create the UnknownUrlExceptionMapper class.
src/main/java/io/openliberty/guides/inventory/client/UnknownUrlExceptionMapper.java

UnknownUrlExceptionMapper.java

link:finish/src/main/java/io/openliberty/guides/inventory/client/UnknownUrlExceptionMapper.java[]

The handles() method inspects the HTTP response code to determine whether an exception is thrown for the specific response, and the toThrowable() method returns the mapped exception.

Injecting the client with dependency injection

Now, instantiate the SystemClient interface and use it in the inventory service. If you want to connect only with the default host name, you can easily instantiate the SystemClient with CDI annotations. CDI injection simplifies the process of bootstrapping the client.

First, you need to define the base URL of the SystemClient instance. Configure the default base URL with the MicroProfile Config feature. This feature is enabled for you in both server.xml and pom.xml files.

Create the configuration file.
src/main/webapp/META-INF/microprofile-config.properties

microprofile-config.properties

link:finish/src/main/webapp/META-INF/microprofile-config.properties[]

The config property io.openliberty.guides.inventory.client.SystemClient/mp-rest/url is configured to the default http://localhost:9080/system base URL.

This configuration is automatically picked up by the MicroProfile Config API.

Look at the annotations in the SystemClient interface again.

SystemClient.java

link:finish/src/main/java/io/openliberty/guides/inventory/client/SystemClient.java[]

The @Dependent annotation tells the service that the scope of the interface depends on the class that it is injected into. By default, interfaces have a @Dependent scope unless another scope is defined on the interface.

The @RegisterRestClient annotation registers the interface as a RESTful client. The runtime creates a CDI managed bean for every interface that is annotated with the @RegisterRestClient annotation.

The @Dependent and @RegisterRestClient annotations imply that the interface is manageable through CDI. You must have them in order to inject the client.

Inject the SystemClient interface into the InventoryManager class, which is another CDI managed bean.

Create the InventoryManager class.
src/main/java/io/openliberty/guides/inventory/InventoryManager.java

InventoryManager.java

link:finish/src/main/java/io/openliberty/guides/inventory/InventoryManager.java[]

@Inject and @RestClient annotations inject an instance of the SystemClient called defaultRestClient to the InventoryManager class.

Since the InventoryManager class is @ApplicationScoped, and the SystemClient CDI bean maintains the same scope through the @Dependent annotation, the client is initialized once per application.

If the hostname parameter is localhost, the service runs the getPropertiesWithDefaultHostName() helper function to fetch system properties. The helper function invokes the system service by calling the defaultRestClient.getProperties() method.

Building the client with RestClientBuilder

The inventory service might also connect with a host other than the default localhost host. Then, you cannot configure a base URL that is not yet known. Therefore, set the host name as a variable and build the client by using the RestClientBuilder method. You can customize the base URL from the host name attribute.

Look at the getPropertiesWithGivenHostName() method in the src/main/java/io/openliberty/guides/inventory/InventoryManager.java file.

InventoryManager.java

link:finish/src/main/java/io/openliberty/guides/inventory/InventoryManager.java[]

The host name is provided as a parameter. This method first assembles the base URL that consists of the new host name. Then, the method instantiates a RestClientBuilder builder with the new URL, registers the response exception mapper, and builds the SystemClient instance.

Similarly, call the customRestClient.getProperties() method to invoke the system service.

When the server is running, select either approach to fetch your system properties:

  • Visit the http://localhost:9080/inventory/systems/localhost URL. The URL retrieves the system property information for localhost host name by invoking the http://localhost:9080/system/properties service.

  • Get your FQDN first. Then, visit the http://localhost:9080/inventory/systems/{your_hostname} URL by replacing {your_hostname} with your FQDN, which retrieves your system properties by invoking the http://{your_hostname}:9080/system/properties service.

Testing the application

Create the RestClientTest class.
src/test/java/it/io/openliberty/guides/client/RestClientTest.java

RestClientTest.java

link:finish/src/test/java/it/io/openliberty/guides/client/RestClientTest.java[]

Each test case tests one of the methods for instantiating a RESTful client.

The testDefaultLocalhost() test fetches and compares system properties from the http://localhost:9080/inventory/systems/localhost URL.

The testRestClientBuilder() test gets your IP address. Then, use your IP address as the host name to fetch your system properties and compare them.

In addition, a few endpoint tests are provided for you to test the basic functionality of the inventory and system services. If a test failure occurs, you might have introduced a bug into the code.

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running it.io.openliberty.guides.system.SystemEndpointTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.377 sec - in it.io.openliberty.guides.system.SystemEndpointTest
Running it.io.openliberty.guides.inventory.InventoryEndpointTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.379 sec - in it.io.openliberty.guides.inventory.InventoryEndpointTest
Running it.io.openliberty.guides.client.RestClientTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.121 sec - in it.io.openliberty.guides.client.RestClientTest

Results :

Tests run: 3, Failures: 0, Errors: 0, Skipped: 0

To see whether the tests detect a failure, change the base URL in the configuration file so that when the inventory service tries to access the invalid URL, an UnknownUrlException is thrown. Rerun the Maven build. You see a test failure occur.

Great work! You’re done!

You just invoked a remote service by using a template interface with MicroProfile Rest Client in Open Liberty.

Feel free to try one of the related guides. They demonstrate more technologies that you can learn and expand on what you built here.

You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.