REST Client module
Developer productivity Bundled: Community edition
Edition |
CE |
License |
|
Issues |
|
Maven site |
|
Latest |
3.0.0 |
Magnolia REST Client module enables easy creation, configuration and usage of REST clients. Besides the ability to configure REST clients, the module also:
-
Provides the REST Client app to test and debug configured clients.
-
Includes
restfn
templating functions that give access to REST clients within FreeMarker template scripts.
This page describes the module, explains how to install it and gives a quick reference how to declare and configure REST clients.
The ability to use REST clients in the UI (in apps and search result supplier) is a DX Core feature only, provided by the UI Framework REST Extensions module (artifactId |
Installing with Maven
Maven is the easiest way to install the module. Add the following to your bundle:
<dependency>
<groupId>info.magnolia.restclient</groupId>
<artifactId>magnolia-rest-client</artifactId>
<version>3.0.0</version> (1)
</dependency>
1 | Should you need to specify the module version, do it using <version> . |
<dependency>
<groupId>info.magnolia.restclient</groupId>
<artifactId>magnolia-rest-client-app</artifactId>
<version>3.0.0</version> (1)
</dependency>
1 | Should you need to specify the module version, do it using <version> . |
Module description
-
magnolia-rest-client
- Defines the API for a Magnolia REST client definition class (to configure), for a REST client factory (to create instances) and for a registry (to obtain configured clients). -
magnolia-rest-client-app
- Installs the client app to test and debug configured REST clients. You can test your clients in the app before using them in template scripts, models or other Java classes.
Configuration
REST clients can be configured within all Magnolia modules in the
restClients
folder.
Example: A declaration of a client called programming-quotations
.
For the full use case, see Hello Magnolia - with content via REST, an extension of the Hello Magnolia introductory tutorial:
baseUrl: https://programming-quotes-api.herokuapp.com
restCalls:
random:
method: get
entityClass: com.fasterxml.jackson.databind.JsonNode
path: /quotes/random/lang/en
Additional examples of configuration and use are available on the Example REST client configurations page.
Most of the configurations listed on that page are from the declarative-rest-demo
light modules stored in our Bitbucket repository:
-
(WARNING: Only available for the Magnolia DX Core Edition.)
REST Client properties
Property | Description | ||
---|---|---|---|
|
required Add a node for each REST client. The name is arbitrary, but it is good practice to use a descriptive name. The node name is used when obtaining instances of clients. |
||
|
required Base URL of the REST endpoint to connect with the client.
|
||
|
optional, default is `info.magnolia.rest.client.ConfiguredRestClientDefinition` REST client definition class.
In additional to the default class, you may use also the |
||
|
optional, default is `info.magnolia.rest.client.factory.DefaultClientFactory` The factory class. The default factory class is used with the The info.magnolia.openapi.client.factory.OpenApiClientFactory class is used with |
||
|
required if Full path (URL or file) to the resource containing an OpenAPI schema. |
||
|
optional Custom class that specifies the client builder. Allows you to configure the client ex post, without the need to create a new factory or extend it. See also Jakarta RESTful Web Services. |
||
|
optional List of components (for example Registered components will be executed on every request. Example configuration
|
||
|
optional, default is Enables or disables the client. |
||
|
optional Custom class that handles the HTTP standard response exceptions such as code 404 - Any |
||
|
optional Overrides the name assigned to the client through the node name. The name should be unique. By default, file name is used in a file-based client definition. |
||
|
optional List of info.magnolia.rest.client.proxy.ProxyDefinition objects. You can use definitions with |
REST calls
Property | Description | ||||
---|---|---|---|---|---|
|
|||||
|
optional List of REST call configurations. |
||||
|
required Add a node for each call configuration. The name is arbitrary but should be unique in the configuration. |
||||
|
required Entity type of the REST call, for example:
You can also use your own Java class. Jackson will try to map a response to it. For example:
|
||||
|
required Definition of the REST method: |
||||
|
required Definition of the path for the REST call. |
||||
|
optional Object containing request body.
For example, to send this:
you need to convert it to and send this:
Likewise, none of the following will work:
|
||||
|
optional List of accepted request cookies.
|
||||
|
optional List of default values.
Default values can be used in any query parameter and can be overridden using For example, the default values
|
||||
|
optional List of accepted request headers. Example:
|
||||
|
optional List of request query parameters. Example using a template
|
||||
|
optional A Example:
|
||||
|
optional Name of a configured security scheme the call uses. |
Trust store
If the target server uses a self-signed certificate, you can add a trust store configuration to the client.
Property | Description |
---|---|
|
|
|
optional A node for a trust store configuration. |
|
required String specifying the password for the certification trust store. Required when used with a REST client definition with SSL support. |
|
required String specifying the location of the certification trust store. Required when used with a REST client definition with SSL support. |
|
required String specifying the type of the certification trust store. Required when used with a REST client definition with SSL support. |
|
optional, default is Setting the property to |
Security scheme
If the REST API service needs an authentication of a REST call, you can configure a security (authentication) scheme under the securitySchemes
node of the client configuration.
Two security handlers are available out of the box:
Example configuration
Example configuration of a security scheme named b1
, with a binding to a REST call named myCommand
via the securityScheme
property.
baseUrl: http://localhost:8080/magnoliaPublic
securitySchemes: # define one or more schemes
b1:
$type: basic
username: superuser
password: superuser
restCalls:
myCommand:
method: post
entityClass: com.fasterxml.jackson.databind.JsonNode
path: /.rest/commands/v2/myCatalog/myCommand
securityScheme: b1 # set the scheme for the call
Basic security scheme
Property | Description |
---|---|
|
|
|
optional List of basic security scheme configurations. |
|
required Scheme name. The name is arbitrary. |
|
required The basic security must use the info.magnolia.rest.client.authentication.definition.BasicSecuritySchemeDefinition class. Alternatively, |
|
optional Username used in the basic security scheme.
Template values(
|
|
optional Password used in the basic security scheme.
Template values (
|
Bearer security scheme
Property | Description |
---|---|
|
|
|
optional List of bearer security scheme configurations. |
|
required Scheme name. The name is arbitrary. |
|
required The bearer scheme must use the info.magnolia.rest.client.authentication.definition.BearerSecuritySchemeDefinition class. Alternatively, |
|
required Name of the REST client that invokes the authentication call. |
|
required Name of the configured authentication REST call in the REST client. |
|
required The name of the property containing token information in the response. For example:
|
|
optional Node with specification of a bearer token expiration resolution. The following resolution types (classes) are available:
|
|
required The class used to resolve token expiration, for example info.magnolia.rest.client.authentication.definition.DurationExpiryDefinition. Alternatively, a |
|
optional Mandatory for expiration Specification of the date-time pattern that needs to be parsed to obtain the expiry value. Example:
|
|
optional Name of the property containing expiration information. Example:
|
|
optional, default is `MILLISECONDS` Used for expiration Time unit of expiration duration.
If the service requires a different unit other than Example:
|
|
optional Mandatory for expiration Specification of the time zone in whose context the expiration is to be evaluated. Example:
|
Timeouts
Property | Description |
---|---|
|
|
|
optional A node to configure how request timeouts should be handled. |
|
optional Time limit (in seconds) within which the connection to the server must be made, otherwise an exception is thrown. |
|
optional The property takes a boolean value, which controls fallbacking to cache. If set to See also Cache configuration properties. |
|
optional Time limit (in seconds) within which the data-read time of the specified server must be made, otherwise an exception is thrown. |
|
optional Custom class that handles timeout (request processing) exceptions ( If no custom handler is provided, the default one will be used. |
Using environment variables
You can use environment variables in plain YAML configuration files (not in YAML decorator files).
Let’s say you want to target a different url and supply different credentials depending on which Magnolia environment is making the call.
For example if it’s your UAT or Prod environment.
In this scenario, you could define three environment variables API_BASE_URL
, API_USER
, API_PWD
and use them in your definitions.
baseUrl: !env ${API_BASE_URL}/example/todos (1)
securitySchemes:
basic:
$type: basic
username: !env ${API_USER} (1)
password: !env ${API_PWD} (1)
1 | The environment variables that you export from your terminal or IDE.
|
Hiding sensitive information
In the path
, queryParameters
, headers
, cookies
and body
properties, and in the username
and password
properties of the basic
security scheme, you can use the password template ({@password:<passwordIdentifier>}
) and the respective password identifier from the Passwords app to hide password values in the requests.
Example:
baseUrl: https://example.com
restCalls:
foo:
headers:
api_key: '{@password:<UUID>}'
Service interface declaration
For restfn
functions that utilize a service, you need to declare a service as a Java interface using javax.ws.rs
annotations.
The interface must be part of a Magnolia Maven module.
You can use these service interfaces in restfn
and REST clients.
Example: An interface to get a client that requests api.icndb.com/jokes/random?firstName=John&lastName=Doe
.
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
public interface IcndbService {
@GET
@Path("/jokes/{select}")
@Produces(MediaType.APPLICATION_JSON)
JsonNode joke(@PathParam("select") String select, @QueryParam("firstName") String firstName, @QueryParam("lastName") String lastName);
}
-
The return type of a method and the
@Produces
declaration must correspond with each other. In the example above, the#joke
method returns anorg.codehaus.jackson.JsonNode
object, which fits well together with@Produces(MediaType.APPLICATION_JSON)
. -
The value of the
@Path
annotation is relative to thebaseUrl
of this Java client. In this example, the relative URL starts with/jokes
followed by a parameter. ThebaseUrl
itself is defined in the configuration. -
Create a method for each sub-resource / parameters combination you need.
Handling errors and exceptions
info.magnolia.rest.client.exception.handler.RestClientExceptionHandler in module version 2 allows you to access response codes and exceptions and deal with them the way you need. See the example template scripts below that use the following client configuration:
baseUrl: 'http://httpbin.org/'
class: 'info.magnolia.rest.client.ConfiguredRestClientDefinition'
clientFactoryClass: 'info.magnolia.rest.client.factory.DefaultClientFactory'
restCalls:
requestCode:
method: 'GET'
entityClass: 'java.lang.String'
path: 'status/{code}'
defaultValues:
code: 404
Get Status
Display the response status code (https://jakarta.ee/specifications/platform/8/apidocs/javax/ws/rs/core/response#getStatusInfo--):
[#assign code500Call = restfn.call("errors", "requestCode", {"code": 500})]
<p>
<b>code500Call:</b> ${code500Call.getEntity()?has_content?then(code500Call.getEntity(), code500Call.getStatus())}
</p>
Get StatusInfo
Display the response status information (https://jakarta.ee/specifications/platform/8/apidocs/javax/ws/rs/core/response#getStatusInfo--):
[#assign code404Call = restfn.call("errors", "requestCode", {"code": 404})]
<p>
<b>code404Call:</b> ${code404Call.getEntity()?has_content?then(code404Call.getEntity(), code404Call.getStatusInfo())}
</p>
See also RFC-2616: 10 Status Code Definitions.
Non-existing client configuration
The script refers to a REST client definition (errors1234
) that doesn’t exist:
[#assign wrongClientNameCall = restfn.call("errors1234", "requestCode1234")]
<p>
<b>wrongClientNameCall:</b> ${wrongClientNameCall.getEntity()?has_content?then(wrongClientNameCall.getEntity(), wrongClientNameCall.getStatus())}
</p>
Testing clients in the Rest Client app
See the REST Client app page.
See also info.magnolia.rest.client.RestClient.