You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 128 Next »


This page is intended for developers who want to start using Magnolia REST features.

In this page, we:


Key points

This section is a very brief summary of the most important things from the sections below.

To use Magnolia REST features:

  • Set up Magnolia with version 5.6 or higher; you may want to use a preconfigured Magnolia bundle.
  • Make sure your bundle contains at least the Magnolia REST modules magnolia-rest-integrationmagnolia-rest-servicesmagnolia-rest-content-delivery (version 2.0 or higher). See REST module - Installing if needed.
  • Design a security strategy with custom users to access the REST endpoint. To start immediately or for testing purposes, you can use superuser on the author instance and anonymous user on the public instance at your own risk.
  • Provide YAML configuration to enable the usage of the delivery endpoint in a light module.


    delivery-base-definition.yaml
    class: info.magnolia.rest.delivery.jcr.v1.JcrDeliveryEndpointDefinition
    params:
      website:
        depth: 2
        nodeTypes:
          - mgnl:page
          - mgnl:area
          - mgnl:component
        childNodeTypes:
          - mgnl:area
          - mgnl:component
        rootPath: /
        includeSystemProperties: false
    Read Delivery endpoint API - YAML configuration for further details.

  • cURL:

    curl -X GET 'http://localhost:8080/magnoliaPublic/.rest/delivery/website/v1/travel/about'
    and GET a REST.

Setup

In this section, we assume you are using a Magnolia bundle version 5.6 or higher and you know how to:

  • Install Magnolia.
  • Set the magnolia.resources.dir property in the magnolia.properties file.
  • Start and stop Magnolia.

Best practice

We recommend you have one common directory for the magnolia.resources.dir on both magnoliaAuthor and magnoliaPublic webapps. We will use it later on for a shared configuration.

If you do not know how to do all of this, see Set up a Magnolia bundle with all REST modules - step by step instead.

Required modules

The modules listed below are required to use all Magnolia REST features in a productive context:

  • magnolia-rest-integration
  • magnolia-rest-services
  • magnolia-rest-content-delivery

When using a preconfigured Magnolia bundle, your webapps already contain these three modules. If you are using a custom webapp or bundle, make sure your custom setup contains the modules listed above. See REST module - Installing if needed.

When developing new features, it can be helpful to use the magnolia-rest-tools module which enables Swagger UI tools. 

Enabling Swagger UI tools - magnolia-rest-tools

The Swagger framework is supported by a set of core tools for designing, building, and documenting RESTful APIs.

Source: https://swagger.io/tools/

Magnolia provides integration with Swagger tools directly in the Admin UI.

Swagger tools are for development and testing purposes only.

If you do not want to use the Swagger UI tools, skip ahead to security settings.

Installing the magnolia-rest-tools module

To enable swagger you must add magnolia-rest-tools to your webapp(s). 

With Maven

Add the following snippet to the pom file of your webapp:

Error rendering macro 'artifact-maven-dependencies-snippet-macro'

com.sun.jersey.api.client.ClientHandlerException: java.net.NoRouteToHostException: No route to host (Host unreachable)

With a downloaded bundle

If you are running a preconfigured Magnolia Tomcat bundle:

  • Stop the Tomcat server.
  • Download the REST tools bundle 

    Error rendering macro 'artifact-resource-macro'

    com.sun.jersey.api.client.ClientHandlerException: java.net.NoRouteToHostException: No route to host (Host unreachable)

    .
  • Unzip the download and copy* all the files to: 
    • $tomcat/webapps/magnoliaAuthor/WEB-INF/lib
    • $tomcat/webapps/magnoliaPublic/WEB-INF/lib (if the directory already exists)

* The zip file may contain .jar files which are already present in the WEB-INF/lib folder of your webapps.

Set the Swagger API base path

The Swagger API explorer tool searches for the API at a path set in /modules/rest-tools/config/apiBasepath. The default value is  http://localhost:8080/.rest . The value for this property must match the following pattern:

<protocol>://<hostname>:<port>/<context>/.rest

When using one of Magnolia's preconfigured bundles running on localhost, set the property to http://localhost:8080/magnoliaAuthor/.rest .

Set the path to where REST services reside on your system. If you run the standard Magnolia bundle and work on the author instance, set the path to  http://localhost:8080/magnoliaAuthor/.rest .


Node nameValue

 
modules


 
rest-tools


 
config


 
apiBasepath

http://localhost:8080/magnoliaAuthor/.rest

After setting the base path, restart Magnolia.

Swagger UI tools is in Dev > REST Tools.

Set up a Magnolia bundle with all REST modules - step by step

This section provides step by step instructions to set up a Magnolia bundle that contains all REST modules including the magnolia-rest-tools module to use Swagger UI tools. The procedure uses Magnolia CLI. If you are an experienced Magnolia user, you can skip this and set up Magnolia in your preferred style.

StepInstructions
1

Choose a directory to work in.

Open a shell and change to the directory of your choice. In our example, we use the directory ~/dev/mgnl-rest-test-base.

cd ~/dev/mgnl-rest-test-base
2

Download a bundle with Magnolia CLI.

mgnl jumpstart

Jumpstart downloads and extracts the latest version of magnolia-community-demo-bundle which comes with Tomcat server. Use the -e option to get the magnolia-enterprise-pro-demo-bundle - which will prompt for enterprise credentials. See jumpstart for further options.

Jumpstart also sets the property magnolia.resources.dir in the file magnolia.properties.

Once jumpstart is executed, your directory looks like this:

mgnl-rest-test-base/
├── apache-tomcat
├── light-modules
└── magnolia.zip

We will need the light-modules folder later on. (warning) Do not start the Tomcat server yet.

3

Add magnolia-rest tools to your bundle.

Download the REST tools bundle 

Error rendering macro 'artifact-resource-macro'

com.sun.jersey.api.client.ClientHandlerException: java.net.NoRouteToHostException: No route to host (Host unreachable)

into a temporary folder. Unzip it and copy all the files from the unzipped folder into ~/dev/mgnl-rest-test-base/apache-tomcat/webapps/magnoliaAuthor/WEB-INF/lib. Some of the files may already be there.

4

Start Magnolia.

You are ready to start the Tomcat server for the first time. Go to the "root" directory (/dev/mgnl-rest-test-base) and execute the CLI command start:

cd ~dev/mgnl-rest-test-base
mgnl start

(info) During the initial start up, Magnolia installs a lot of configuration data and demo content bootsrapped with its modules - this may take some time.

5

Log in to the author instance.

In your preferred browser, open the URL http://localhost:8080/magnoliaAuthor/ and log in as user superuser with the password superuser.

Now you are nearly done. Have a look around Magnolia. Access the public instance with the URL http://localhost:8080/magnoliaPublic/ .

6

Set the Swagger base API path.

In order to properly use the Swagger UI tools - which are used for development only - you must change one property in the configuration.

On the UAdmin, open the Configuration app and find the node /modules/rest-tools/config. (You can use the URL http://localhost:8080/magnoliaAuthor/.magnolia/admincentral#app:configuration:browser;/modules/rest-tools/config:treeview: to go there directly.)

Open the config folder and change the value of the apiBasepath property to: http://localhost:8080/magnoliaAuthor/.rest

7

Restart Magnolia.

Go to the shell where you started Magnolia.

To stop the server, press cmd + C (on Mac) or ctrl + C (on Windows). Give the server some time to properly shut down.

Then start it again:

cd ~dev/mgnl-rest-test-base
mgnl start

Security settings

We have warned you

REST endpoints are a powerful tool but can also make your site very vulnerable. Make sure you understand how to implement a strong security strategy to safeguard your system..

Please read and understand REST security before enabling and using the REST endpoints on a productive environment.

In the context of this tutorial to get started, you will use users with roles provided by the default setup of the the Magnolia bundle.

Using superuser on the author context - for testing reasons only!

On the author context the superuser is granted:

  • Read/Write access for the path / on every JCR workspace - granted by the role  superuser.
  • Web access for the HTTP methods GETPUTPOST and DELETE for the path /magnoliaAuthor/.rest* - granted by the role rest-admin.

Note that superuser is given a lot of power. Use it carefully in the context of this tutorial.  But never use superuser on a productive environment.

Using anonymous user on the public context

The public context typically is visited by users which do not authenticate. Nevertheless, such visits are done as anonymous user - which also has some permissions.

On the public context anonymous user is granted:

  • Read access on the path / for the JCR workspaces websitedamgoogleSitemapscategorytours
  • Web access for the HTTP method GET on the path  path /magnoliaAuthor/.rest/delivery/*

As you can see, anonymous user only has read access and can only access the Delivery endpoint. That is sufficient for the moment.

On a productive environment - we highly recommend to create custom REST roles granting specific access for specific use cases.

The endpoints - an overview

Magnolia provides out of the box the following REST endpoints:

EndpointHTTP methodsSwagger UI enabled
delivery

GET

Read node.
Query nodes.

----
nodes

GET

PUT

POST

DELETE

Read nodeCreate nodeUpdate nodeDelete node
properties

GET

PUT

Create property

POST

Update property

DELETE

Read propertyDelete property
commands

-

-

POST

Execute command

-

If you want to use REST to create, update and delete content - we recommend using the Nodes endpoint which supports all required operations. If you mainly want to read data - consider using the Delivery endpoint. It provides a very handy formatted JSON and can be customized and configured with YAML via light module. With the Commands endpoint you can trigger commands. And Cache endpoint deals with cache. And you always can create your own custom endpoints - for inspiration see How to create a custom Java based REST endpoint

Tools to test REST requests

On this section we propose some tools to test the REST API - without the need to develop a REST consuming client application. Testing your REST requests is handy when you are developing client apps and similar things which will interact with the REST endpoints.

Browser

PositiveFor instance Firefox displays JSON and XML in a very well readable format. 
Negative

A browser provides only limited control to tailor a request without further add-ons. Requests are sent as GET and you cannot add more request headers out of the box.

Tips

If you want to test on REST resources via GET, which requires authetication (to get assigned roles not provided to anonymous user - login at Magnolia first, open a new tab on the same window (using the same session) and then requesting the REST resource.

Upgrade the browser with add-ons to extend its possibilities to controll the request.


 

cURL

cURL is a command line tool. It can be used on most of the well known operating systems.

Downloadhttps://curl.haxx.se/download.html
PositiveVery flexible to tailor the request (method, request headers, user credentials, etc.). Response can be further processed.
NegativeNot everybody likes command line tools. The response is not easy to read without further tooling. No out of the box automatic URL encoding.
Tips

On the first atempt of a request use the -i option to display all response headers.

If the response body is fine and delivers JSON, pretty print and colorize the response body with tools such as jq.

Swagger UI tools

If you have not installed magnolia-rest-tools with the swagger UI tools, skip this section, or see above about how to enable the swagger tools.

Positive

Seamless integrated into the Magnolia UAdmin. Comfortable to use form based interface.

Negative

The endpoints require specific annotations to make them appear on the swagger UI tools. Delivery endpoint is not annotated and will not appear on the swagger tools. REST request is sent by the user which logged into Magnolia; cumbersome to test with different users.

Starting the swagger tools

Go to Dev > REST Tools.

When you open the the Magnolia REST Tools app, you should see something similar to this screen: 

The Swagger UI lists the bundled endpoints which already have Swagger annotations. These are the endpoints from magnolia-rest-services module (propertiesv1, commandsv2, nodesv1) and one from the cache-browser-app (cachev1).

Now click on one of the links - it will open a submenu which shows all supported operations provided by the endpoint.

Click List operations or Expand operations to get the detail forms for the operations.

Here is an example for GET of the nodes endpoint:

Enter values at least for the mandatory parameters and click the button Try it out!.

Swagger will show the response code, the response headers and the response body:

Using the delivery endpoint

The Delivery endpoint is the latest REST API provided by Magnolia out of the box. Use it for obtaining JCR data as JSON. 

Besides security settings - you must provide YAML based configuration for the delivery endpoint - otherwise the endpoint can not serve JSON.

Configuring the delivery enpoint

For the YAML based configuration of the delivery endpoint - let us create a light module.

Within the light-modules folder - which is configured with the property magnolia.resources.dir, see above - create the following structure:

define-delivery-endpoint/
└── restEndpoints/
    └── delivery-base-definition.yaml

To start with - the file delivery-base-definition.yaml can look like this:

delivery-base-definition.yaml
class: info.magnolia.rest.delivery.jcr.v1.JcrDeliveryEndpointDefinition
params:
  website:
    depth: 2
    nodeTypes:
      - mgnl:page
      - mgnl:area
      - mgnl:component
    childNodeTypes:
      - mgnl:area
      - mgnl:component
    rootPath: /
    includeSystemProperties: false
To get all the details - please refer to Delivery endpoint API - YAML configuration.

For the time being, you should know the following things:

  • Line 3: website is the name of the so called "endpoint prefix" - in our case it is also the name of a JCR workspace. We will use the value of the endpoint prefix later on within the REST request URL.
  • Everything below line 3 in the file above defines this endpoint prefix.
  • You can define further endpoint prefixes.
  • Make sure you have only one YAML based endpoint definition.

Reading website content with the delivery endpoint

With the given configuration above - you are ready to send REST requests to your Magnolia instance.

Let us fetch the content of the page /travel/about on the website workspace. Have a look at Delivery endpoint API - readNode - to understand how to compose the URL. We need:

  • The name of  endpoint prefix => website
  • The relative path of the node - relative to what is defined in the configuration as rootPath: => travel/about

URL => /.rest/delivery/website/v1/travel/about

Now add the "context" (the name of the webapp), the domain and the protocoll - and you get this URLs:

The first URL, which goes to the public context, you can request with the browser as anonymous user (without authentication). For the second request you must authenticate.

To test these URLs with cURL, use the following commands:

curl -X GET 'http://localhost:8080/magnoliaPublic/.rest/delivery/website/v1/travel/about'

curl -X GET 'http://localhost:8080/magnoliaAuthor/.rest/delivery/website/v1/travel/about' \
-u superuser:superuser


#trackbackRdf ($trackbackUtils.getContentIdentifier($page) $page.title $trackbackUtils.getPingUrl($page))
  • No labels