Quarkus - Using the REST Client

This guide explains how to use the MicroProfile REST Client in order to interact with REST APIs with very little effort.

there is another guide if you need to write server JSON REST APIs.

Prerequisites

To complete this guide, you need:

  • less than 15 minutes

  • an IDE

  • JDK 1.8+ installed with JAVA_HOME configured appropriately

  • Apache Maven 3.6.2+

Solution

We recommend that you follow the instructions in the next sections and create the application step by step. However, you can go right to the completed example.

Clone the Git repository: git clone [https://github.com/quarkusio/quarkus-quickstarts.git](https://github.com/quarkusio/quarkus-quickstarts.git), or download an archive.

The solution is located in the rest-client-quickstart directory.

Creating the Maven project

First, we need a new project. Create a new project with the following command:

  1. mvn io.quarkus:quarkus-maven-plugin:1.7.6.Final:create \
  2. -DprojectGroupId=org.acme \
  3. -DprojectArtifactId=rest-client-quickstart \
  4. -DclassName="org.acme.rest.client.CountriesResource" \
  5. -Dpath="/country" \
  6. -Dextensions="rest-client, resteasy-jsonb"
  7. cd rest-client-quickstart

This command generates the Maven project with a REST endpoint and imports the rest-client and resteasy-jsonb extensions.

If your application does not expose any JAX-RS endpoints (eg. a command mode application), use the rest-client-jsonb or the rest-client-jackson extension instead.

If you already have your Quarkus project configured, you can add the rest-client and the rest-client-jsonb extensions to your project by running the following command in your project base directory:

  1. ./mvnw quarkus:add-extension -Dextensions="rest-client,resteasy-jsonb"

This will add the following to your pom.xml:

  1. <dependency>
  2. <groupId>io.quarkus</groupId>
  3. <artifactId>quarkus-rest-client</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>io.quarkus</groupId>
  7. <artifactId>quarkus-resteasy-jsonb</artifactId>
  8. </dependency>

Setting up the model

In this guide we will be demonstrating how to consume part of the REST API supplied by the restcountries.eu service. Our first order of business is to setup the model we will be using, in the form of a Country POJO.

Create a src/main/java/org/acme/rest/client/Country.java file and set the following content:

  1. package org.acme.rest.client;
  2. import java.util.List;
  3. public class Country {
  4. public String name;
  5. public String alpha2Code;
  6. public String capital;
  7. public List<Currency> currencies;
  8. public static class Currency {
  9. public String code;
  10. public String name;
  11. public String symbol;
  12. }
  13. }

The model above is only a subset of the fields provided by the service, but it suffices for the purposes of this guide.

Create the interface

Using the MicroProfile REST Client is as simple as creating an interface using the proper JAX-RS and MicroProfile annotations. In our case the interface should be created at src/main/java/org/acme/rest/client/CountriesService.java and have the following content:

  1. package org.acme.rest.client;
  2. import org.eclipse.microprofile.rest.client.inject.RegisterRestClient;
  3. import org.jboss.resteasy.annotations.jaxrs.PathParam;
  4. import javax.ws.rs.GET;
  5. import javax.ws.rs.Path;
  6. import javax.ws.rs.Produces;
  7. import java.util.Set;
  8. @Path("/v2")
  9. @RegisterRestClient
  10. public interface CountriesService {
  11. @GET
  12. @Path("/name/{name}")
  13. @Produces("application/json")
  14. Set<Country> getByName(@PathParam String name);
  15. }

The getByName method gives our code the ability to query a country by name from the REST Countries API. The client will handle all the networking and marshalling leaving our code clean of such technical details.

The purpose of the annotations in the code above is the following:

  • @RegisterRestClient allows Quarkus to know that this interface is meant to be available for CDI injection as a REST Client

  • @Path, @GET and @PathParam are the standard JAX-RS annotations used to define how to access the service

  • @Produces defines the expected content-type

While @Consumes and @Produces are optional as auto-negotiation is supported, it is heavily recommended to annotate your endpoints with them to define precisely the expected content-types.

It will allow to narrow down the number of JAX-RS providers (which can be seen as converters) included in the native executable.

Create the configuration

In order to determine the base URL to which REST calls will be made, the REST Client uses configuration from application.properties. The name of the property needs to follow a certain convention which is best displayed in the following code:

  1. # Your configuration properties
  2. org.acme.rest.client.CountriesService/mp-rest/url=https://restcountries.eu/rest # (1)
  3. org.acme.rest.client.CountriesService/mp-rest/scope=javax.inject.Singleton # (2)
1Having this configuration means that all requests performed using org.acme.rest.client.CountriesService will use https://restcountries.eu/rest as the base URL. Using the configuration above, calling the getByName method of CountriesService with a value of France would result in an HTTP GET request being made to https://restcountries.eu/rest/v2/name/France.
2Having this configuration means that the default scope of org.acme.rest.client.CountriesService will be @Singleton. Supported scope values are @Singleton, @Dependent, @ApplicationScoped and @RequestScoped. The default scope is @Dependent. The default scope can also be defined on the interface.

Note that org.acme.rest.client.CountriesService must match the fully qualified name of the CountriesService interface we created in the previous section.

To facilitate the configuration, you can use the @RegisterRestClient configKey property that allows to use another configuration root than the fully qualified name of your interface.

  1. @RegisterRestClient(configKey="country-api")
  2. public interface CountriesService {
  3. [...]
  4. }
  1. # Your configuration properties
  2. country-api/mp-rest/url=https://restcountries.eu/rest #
  3. country-api/mp-rest/scope=javax.inject.Singleton # /

Update the JAX-RS resource

Open the src/main/java/org/acme/rest/client/CountriesResource.java file and update it with the following content:

  1. import org.eclipse.microprofile.rest.client.inject.RestClient;
  2. import org.jboss.resteasy.annotations.jaxrs.PathParam;
  3. import javax.inject.Inject;
  4. import javax.ws.rs.GET;
  5. import javax.ws.rs.Path;
  6. import javax.ws.rs.Produces;
  7. import javax.ws.rs.core.MediaType;
  8. import java.util.Set;
  9. @Path("/country")
  10. public class CountriesResource {
  11. @Inject
  12. @RestClient
  13. CountriesService countriesService;
  14. @GET
  15. @Path("/name/{name}")
  16. @Produces(MediaType.APPLICATION_JSON)
  17. public Set<Country> name(@PathParam String name) {
  18. return countriesService.getByName(name);
  19. }
  20. }

Note that in addition to the standard CDI @Inject annotation, we also need to use the MicroProfile @RestClient annotation to inject CountriesService.

Update the test

We also need to update the functional test to reflect the changes made to the endpoint. Edit the src/test/java/org/acme/rest/client/CountriesResourceTest.java file and change the content of the testCountryNameEndpoint method to:

  1. package org.acme.rest.client;
  2. import io.quarkus.test.junit.QuarkusTest;
  3. import org.junit.jupiter.api.Test;
  4. import static io.restassured.RestAssured.given;
  5. import static org.hamcrest.CoreMatchers.is;
  6. @QuarkusTest
  7. public class CountriesResourceTest {
  8. @Test
  9. public void testCountryNameEndpoint() {
  10. given()
  11. .when().get("/country/name/greece")
  12. .then()
  13. .statusCode(200)
  14. .body("$.size()", is(1),
  15. "[0].alpha2Code", is("GR"),
  16. "[0].capital", is("Athens"),
  17. "[0].currencies.size()", is(1),
  18. "[0].currencies[0].name", is("Euro")
  19. );
  20. }
  21. }

The code above uses REST Assured‘s json-path capabilities.

Async Support

The rest client supports asynchronous rest calls. Async support comes in 2 flavors: you can return a CompletionStage or a Uni (requires the quarkus-resteasy-mutiny extension). Let’s see it in action by adding a getByNameAsync method in our CountriesService REST interface. The code should look like:

  1. package org.acme.rest.client;
  2. import org.eclipse.microprofile.rest.client.inject.RegisterRestClient;
  3. import org.jboss.resteasy.annotations.jaxrs.PathParam;
  4. import javax.ws.rs.GET;
  5. import javax.ws.rs.Path;
  6. import javax.ws.rs.Produces;
  7. import java.util.concurrent.CompletionStage;
  8. import java.util.Set;
  9. @Path("/v2")
  10. @RegisterRestClient
  11. public interface CountriesService {
  12. @GET
  13. @Path("/name/{name}")
  14. @Produces("application/json")
  15. Set<Country> getByName(@PathParam String name);
  16. @GET
  17. @Path("/name/{name}")
  18. @Produces("application/json")
  19. CompletionStage<Set<Country>> getByNameAsync(@PathParam String name);
  20. }

Open the src/main/java/org/acme/rest/client/CountriesResource.java file and update it with the following content:

  1. package org.acme.rest.client;
  2. import org.eclipse.microprofile.rest.client.inject.RestClient;
  3. import org.jboss.resteasy.annotations.jaxrs.PathParam;
  4. import javax.inject.Inject;
  5. import javax.ws.rs.GET;
  6. import javax.ws.rs.Path;
  7. import javax.ws.rs.Produces;
  8. import javax.ws.rs.core.MediaType;
  9. import java.util.concurrent.CompletionStage;
  10. import java.util.Set;
  11. @Path("/country")
  12. public class CountriesResource {
  13. @Inject
  14. @RestClient
  15. CountriesService countriesService;
  16. @GET
  17. @Path("/name/{name}")
  18. @Produces(MediaType.APPLICATION_JSON)
  19. public Set<Country> name(@PathParam String name) {
  20. return countriesService.getByName(name);
  21. }
  22. @GET
  23. @Path("/name-async/{name}")
  24. @Produces(MediaType.APPLICATION_JSON)
  25. public CompletionStage<Set<Country>> nameAsync(@PathParam String name) {
  26. return countriesService.getByNameAsync(name);
  27. }
  28. }

To test asynchronous methods, add the test method below in CountriesResourceTest:

  1. @Test
  2. public void testCountryNameAsyncEndpoint() {
  3. given()
  4. .when().get("/country/name-async/greece")
  5. .then()
  6. .statusCode(200)
  7. .body("$.size()", is(1),
  8. "[0].alpha2Code", is("GR"),
  9. "[0].capital", is("Athens"),
  10. "[0].currencies.size()", is(1),
  11. "[0].currencies[0].name", is("Euro")
  12. );
  13. }

The Uni version is very similar:

  1. package org.acme.rest.client;
  2. import org.eclipse.microprofile.rest.client.inject.RegisterRestClient;
  3. import org.jboss.resteasy.annotations.jaxrs.PathParam;
  4. import javax.ws.rs.GET;
  5. import javax.ws.rs.Path;
  6. import javax.ws.rs.Produces;
  7. import java.util.concurrent.CompletionStage;
  8. import java.util.Set;
  9. @Path("/v2")
  10. @RegisterRestClient
  11. public interface CountriesService {
  12. // ...
  13. @GET
  14. @Path("/name/{name}")
  15. @Produces("application/json")
  16. Uni<Set<Country>> getByNameAsUni(@PathParam String name);
  17. }

The CountriesResource becomes:

  1. package org.acme.rest.client;
  2. import org.eclipse.microprofile.rest.client.inject.RestClient;
  3. import org.jboss.resteasy.annotations.jaxrs.PathParam;
  4. import javax.inject.Inject;
  5. import javax.ws.rs.GET;
  6. import javax.ws.rs.Path;
  7. import javax.ws.rs.Produces;
  8. import javax.ws.rs.core.MediaType;
  9. import java.util.concurrent.CompletionStage;
  10. import java.util.Set;
  11. @Path("/country")
  12. public class CountriesResource {
  13. @Inject
  14. @RestClient
  15. CountriesService countriesService;
  16. // ...
  17. @GET
  18. @Path("/name-uni/{name}")
  19. @Produces(MediaType.APPLICATION_JSON)
  20. public Uni<Set<Country>> nameAsync(@PathParam String name) {
  21. return countriesService.getByNameAsUni(name);
  22. }
  23. }
Mutiny

The previous snippet uses Mutiny reactive types, if you’re not familiar with them, read the Getting Started with Reactive guide first.

When returning a Uni, every subscription invokes the remote service. It means you can re-send the request by re-subscribing on the Uni, or use a retry as follow:

  1. @Inject @RestClient CountriesResource service;
  2. // ...
  3. service.nameAsync("Greece")
  4. .onFailure().retry().atMost(10);

If you use a CompletionStage, you would need to call the service’s method to retry. This difference comes from the laziness aspect of Mutiny and its subscription protocol. More details about this can be found in the Mutiny documentation.

Package and run the application

Run the application with: ./mvnw compile quarkus:dev. Open your browser to http://localhost:8080/country/name/greece.

You should see a JSON object containing some basic information about Greece.

As usual, the application can be packaged using ./mvnw clean package and executed using the -runner.jar file. You can also generate the native executable with ./mvnw clean package -Pnative.

Using a Mock HTTP Server for tests

Setting up a mock HTTP server, against which tests are run, is a common testing pattern. Examples of such servers are Wiremock and Hoverfly. In this section we’ll demonstrate how Wiremock can be leveraged for testing the CountriesService which was developed above.

First of all, Wiremock needs to be added as a test dependency. For a Maven project that would happen like so:

  1. <dependency>
  2. <groupId>com.github.tomakehurst</groupId>
  3. <artifactId>wiremock-jre8</artifactId>
  4. <scope>test</scope>
  5. <version>${wiremock.version}</version> (1)
  6. </dependency>
1Use a proper Wiremock version. All available versions can be found here.

In Quarkus tests when some service needs to be started before the Quarkus tests are ran, we utilize the @io.quarkus.test.common.QuarkusTestResource annotation to specify a io.quarkus.test.common.QuarkusTestResourceLifecycleManager which can start the service and supply configuration values that Quarkus will use.

For more details about @QuarkusTestResource refer to this part of the documentation.

Let’s create an implementation of QuarkusTestResourceLifecycleManager called WiremockCountries like so:

  1. package org.acme.rest.client;
  2. import java.util.Collections;
  3. import java.util.Map;
  4. import com.github.tomakehurst.wiremock.WireMockServer;
  5. import io.quarkus.test.common.QuarkusTestResourceLifecycleManager;
  6. import static com.github.tomakehurst.wiremock.client.WireMock.*; (1)
  7. public class WiremockCountries implements QuarkusTestResourceLifecycleManager { (2)
  8. private WireMockServer wireMockServer;
  9. @Override
  10. public Map<String, String> start() {
  11. wireMockServer = new WireMockServer();
  12. wireMockServer.start(); (3)
  13. stubFor(get(urlEqualTo("/v2/name/GR")) (4)
  14. .willReturn(aResponse()
  15. .withHeader("Content-Type", "application/json")
  16. .withBody(
  17. "[{" +
  18. "\"name\": \"Ελλάδα\"," +
  19. "\"capital\": \"Αθήνα\"" +
  20. "}]"
  21. )));
  22. stubFor(get(urlMatching(".*")).atPriority(10).willReturn(aResponse().proxiedFrom("https://restcountries.eu/rest"))); (5)
  23. return Collections.singletonMap("org.acme.getting.started.country.CountriesService/mp-rest/url", wireMockServer.baseUrl()); (6)
  24. }
  25. @Override
  26. public void stop() {
  27. if (null != wireMockServer) {
  28. wireMockServer.stop(); (7)
  29. }
  30. }
  31. }
1Statically importing the methods in the Wiremock package makes it easier to read the test.
2The start method is invoked by Quarkus before any test is run and returns a Map of configuration properties that apply during the test execution.
3Launch Wiremock.
4Configure Wiremock to stub the calls to /v2/name/GR by returning a specific canned response.
5All HTTP calls that have not been stubbed are handled by calling the real service. This is done for demonstration purposes, as it is not something that would usually happen in a real test.
6As the start method returns configuration that applies for tests, we set the rest-client property that controls the base URL which is used by the implementation of CountriesService to the base URL where Wiremock is listening for incoming requests.
7When all tests have finished, shutdown Wiremock.

The CountriesResourceTest test class needs to be annotated like so:

  1. @QuarkusTest
  2. @QuarkusTestResource(WiremockCountries.class)
  3. public class CountriesResourceTest {
  4. }

@QuarkusTestResource applies to all tests, not just CountriesResourceTest.

Further reading