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 the configured clients.
- Includes
restfntemplating 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.
Version 2.0 of the module, released with Magnolia 6.2, includes a number of improvements and changes. For an overview, see the Declarative REST section of the Magnolia 6.2 Release Notes.
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 magnolia-rest-client-ui, parent artifactId magnolia-parent-pom-enterprise).
Installing
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 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:
- https://git.magnolia-cms.com/projects/MODULES/repos/rest-client/
- https://git.magnolia-cms.com/projects/ENTERPRISE/repos/rest-client-ui/ (
Only available for the Magnolia DX Core Edition.)
Properties
<rest client name> | 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 REST client definition class. In additional to the default class, you may use also the |
| optional, default is The factory class. The default factory class is used with the The |
| 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 https://en.wikipedia.org/wiki/Java_API_for_RESTful_Web_Services. |
components | optional List of components (for example Registered components will be executed on every request. |
| optional, default is Enables or disables the client. |
| optional Custom class that handles the HTTP standard response exceptions such as code 404 - "Not Found". 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 ProxyDefinition objects. You can use definitions with |
REST call
<rest client name> | |
| 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. |
| 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 baseUrl: https://jsonplaceholder.typicode.com
class: info.magnolia.rest.client.ConfiguredRestClientDefinition
clientFactoryClass: info.magnolia.rest.client.factory.DefaultClientFactory
restCalls:
byUserId:
method: get
entityClass: com.fasterxml.jackson.databind.node.ArrayNode
path: /posts
queryParameters: {userId: "{theUserId}"}
defaultValues: { theUserId: 1 }
single:
method: get
entityClass: com.fasterxml.jackson.databind.JsonNode
path: /posts/{id}
defaultValues: { id: "1" }
|
| 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.
<rest client name> | |
| 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:
Basic security scheme
<rest client name> | |
| optional List of basic security scheme configurations. |
| required Scheme name. The name is arbitrary. |
| required The basic security must use the Alternatively, |
| optional Username used in the basic security scheme. Template values (
|
| optional Password used in the basic security scheme. Template values (
|
Bearer security scheme
<rest client name> | |
| optional List of bearer security scheme configurations. |
| required Scheme name. The name is arbitrary. |
| required The bearer scheme must use the 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 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 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:
|
Timeout configuration properties
<rest client name> | |
| 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. |
Cache configuration properties
<rest client name> | |
| optional A node to configure how caching should be handled. |
| optional, default is Specifies the implementation class. |
| optional Specifies an expiration time (in seconds) for a cache entry. In the default implementation, the expiration time is set to See also the |
Example configuration for caching and timeouts
baseUrl: http://httpbin.org/
cacheConfiguration:
expireIn: 60
timeoutConfiguration:
readTimeout: 5
fallbackToCache: true
restCalls:
delay:
method: GET
entityClass: java.lang.String
path: delay/{delay_period}
defaultValues:
delay_period: 3
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
http://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
@Producesdeclaration must correspond with each other. In the example above, the#jokemethod returns anorg.codehaus.jackson.JsonNodeobject, which fits well together with@Produces(MediaType.APPLICATION_JSON). - The value of the
@Pathannotation is relative to thebaseUrlof this Java client. In this example, the relative URL starts with/jokesfollowed by a parameter. ThebaseUrlitself is defined in the configuration. - Create a method for each sub-resource / parameters combination you need.
Handling errors and exceptions
The 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://docs.oracle.com/javaee/7/api/javax/ws/rs/core/Response.html#getStatus--):
[#assign code500Call = restfn.callForResponse("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://docs.oracle.com/javaee/7/api/javax/ws/rs/core/Response.html#getStatusInfo--):
[#assign code404Call = restfn.callForResponse("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.callForResponse("errors1234", "requestCode1234")]
<p>
<b>wrongClientNameCall:</b> ${wrongClientNameCall.getEntity()?has_content?then(wrongClientNameCall.getEntity(), wrongClientNameCall.getStatus())}
</p>
Non-existing call name
The script refers to a call name (requestCode1234) that doesn't exist:
[#assign wrongNameCall = restfn.callForResponse("errors", "requestCode1234")]
<p>
<b>wrongNameCall:</b> ${wrongNameCall.getEntity()?has_content?then(wrongNameCall.getEntity(), wrongNameCall.getStatus())}
</p>
Testing clients in the Rest Client app
See the REST Client app page.
See also
Magnolia REST Client module API
- RestClient


