Git Product home page Git Product logo

guide-microprofile-rest-client's Introduction

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[role=include]

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[role=include]

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[role=include]

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, where <baseUrl> is the default base URL of the system service. You will see how to configure the base URL in the next section.

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[role=include]

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[role=include]

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[role=include]

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[role=include]

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[role=include]

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[role=include]

@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[role=include]

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[role=include]

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.

guide-microprofile-rest-client's People

Contributors

ahmad-ayyoub avatar andrewdes avatar chyt avatar evelinec avatar gkwan-ibm avatar guidesbot avatar junyisun avatar justineechen avatar kinueng avatar kubik42 avatar neuwerk avatar proubatsis avatar scottkurz avatar sishida avatar wasdevb1 avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.