Consuming a REST service
The REST API library follows the functional programming paradigm along with the Decorator pattern to construct a set of features around REST calls. The examples in this section use the StoreApi from PetStore https://petstore.swagger.io/ REST service to illustrate how you can use the REST API client library with your own OpenAPI Spec compliant service.
How to make a REST call with a default set of fault tolerance parameters
In the following example, the configuration builder builds the configuration using the default settings.
Map<String, Integer> response = Config.builder().build()
.buildAPI(StoreApi.class)
.getInventory();
How to make a REST call with custom fault tolerance parameters
In the following example, the maxAttempt method overwrites the default
retry attempts (3) and sets it to 5.
Map<String, Integer> response = Config.builder()
.eventHandler(RetrySetup.builder()
.maxAttempt(5)
.build())
.build()
.buildAPI(StoreApi.class)
.getInventory();
How to externalize the Rest API client configuration
You can provide the parameters in external files in JSON or YAML format. To retrieve the parameters use the Config object and one of the parseJson(String cfgString) and parseYaml(String cfgString). For more information, see Using externalized configuration files.
Config config = Config.parseYaml(configString).build();
Map<String, Integer> response = config.buildAPI(StoreApi.class)
.getInventory();
How to order the fault tolerance decorators
The order of the fault tolerance decorators is important. In the following example, the
fallback is wrapped within a retry because the fallback is defined
first. Even though maxAttempt is 5, only one retry attempt is made
because the fallback event handler always successfully returns an empty map for any
Throwable exception.
Config config = Config.builder()
.eventHandler(FallbackSetup.builder()
.exceptionType(Throwable.class)
.exceptionHandler(throwable -> Collections.emptyMap())
.build())
.eventHandler(RetrySetup.builder()
.maxAttempt(5)
.build())
.build();
Map<String, Integer> response = config.buildAPI(StoreApi.class).getInventory();
