Creating a hypermedia-driven RESTful web service

duration 30 minutes
Git clone to get going right away:
git clone https://github.com/OpenLiberty/guide-rest-hateoas.git
Copy Github clone command

You’ll explore how to use Hypermedia As The Engine Of Application State (HATEOAS) to drive your RESTful web service on Open Liberty.

What you’ll learn

You will learn how to use hypermedia to create a specific style of a response JSON, which has contents that you can use to navigate your REST service. You’ll build on top of a simple inventory REST service that you can develop with MicroProfile technologies. You can find the service at the following URL:

http://localhost:9080/inventory/hosts

The service responds with a JSON file that contains an array of registered hosts. Each host has a collection of HATEOAS links:

[
  {
    "hostname": "foo",
    "_links": [
      {
        "href": "http://localhost:9080/inventory/hosts/foo",
        "rel": "self"
      }
    ]
  },
  {
    "hostname": "bar",
    "_links": [
      {
        "href": "http://localhost:9080/inventory/hosts/bar",
        "rel": "self"
      }
    ]
  },
  {
  "hostname": "*",
  "_links": [
    {
      "href": "http://localhost:9080/inventory/hosts/*",
      "rel": "self"
    }
  ]
  }
]

What is HATEOAS?

HATEOAS is a constrained form of REST application architecture. With HATEOAS, the client receives information about the available resources from the REST application. The client does not need to be hardcoded to a fixed set of resources, and the application and client can evolve independently. In other words, the application tells the client where it can go and what it can access by providing it with a simple collection of links to other available resources.

Response JSON

When you build a RESTful web service, consider the style of your response files. Whether they are JSON files, XML files, or in some other format, a good practice is to always have them in a clean and organized form. In the context of HATEOAS, each resource must contain a link reference to itself, commonly referred to as self. Each link also needs a relationship to be associated with it, although no strict rules exist as to how you need to format this relationship. Contain the collection of such links within a _links array, which itself must be a direct property of the resource object. The underscore in the _links property is used so that the property does not collide with any existing fields that are named links. In this guide, you will use the following structure of HATEOAS links:

  "_links": [
    {
      "href": ,
      "rel":
    }
  ]

The following example shows two different links. The first link has a self relationship with the resource object and is generated whenever you register a host. The link points to that host entry in the inventory:

  {
    "href": "http://localhost:9080/inventory/hosts/<hostname>",
    "rel": "self"
  }

The second link has a properties relationship with the resource object and is generated if the host system service is running. The link points to the properties resource on the host:

  {
    "href": "http://<hostname>:9080/system/properties",
    "rel": "properties"
  }

Other formats

Although you should stick to the previous format for the purpose of this guide, another common convention has the link as the value of the relationship:

  "_links": {
      "self": "http://localhost:9080/inventory/hosts/<hostname>",
      "properties": "http://<hostname>:9080/system/properties"
  }

Getting started

The fastest way to work through this guide is to clone the Git repository and use the projects that are provided inside:

git clone https://github.com/openliberty/guide-rest-hateoas.git
cd guide-rest-hateoas

The start directory contains the starting project that you will build upon.

The finish directory contains the finished project that you will build.

Try what you’ll build

The finish directory in the root of this guide contains the finished application. Give it a try before you proceed.

To try out the application, first go to the finish directory and run the following Maven goal to build the application inside Open Liberty:

mvn install

Next, run the Maven liberty:start-server goal to start the application inside Open Liberty:

mvn liberty:start-server

After the server runs, you can find your hypermedia-driven inventory service at the following URL:

After you are done checking out the application, stop the Open Liberty server:

mvn liberty:stop-server

Creating the response JSON

Navigate to the start directory.

Begin by building your response JSON, which is composed of the _links array, as well as the name of the host machine.

Linking to inventory contents

As mentioned before, your starting point is an existing simple inventory REST service.

Take a look at the request handlers in the src/main/java/io/openliberty/guides/microprofile/InventoryResource.java file.

InventoryResource.java

 1package io.openliberty.guides.microprofile;
 2
 3import javax.enterprise.context.ApplicationScoped;
 4import javax.inject.Inject;
 5import javax.json.JsonArray;
 6import javax.json.JsonObject;
 7import javax.ws.rs.GET;
 8import javax.ws.rs.Path;
 9import javax.ws.rs.PathParam;
10import javax.ws.rs.Produces;
11import javax.ws.rs.core.Context;
12import javax.ws.rs.core.MediaType;
13import javax.ws.rs.core.UriInfo;
14
15@ApplicationScoped
16@Path("hosts")
17public class InventoryResource {
18
19    @Inject
20    InventoryManager manager;
21
22    @Context
23    UriInfo uriInfo;
24
25    @GET
26    @Produces(MediaType.APPLICATION_JSON)
27    public JsonArray handler() {
28        return manager.getSystems(uriInfo.getAbsolutePath().toString());
29    }
30
31    @GET
32    @Path("{hostname}")
33    @Produces(MediaType.APPLICATION_JSON)
34    public JsonObject getPropertiesForHost(@PathParam("hostname") String hostname) {
35        return (hostname.equals("*")) ? manager.list() : manager.get(hostname);
36    }
37
38}

Since the …​/inventory/hosts/ URL will no longer respond with a JSON representation of the contents of your inventory, you can discard the listContents method and integrate it into the getPropertiesForHost method.

Replace the InventoryResource class.
src/main/java/io/openliberty/guides/microprofile/InventoryResource.java

The contents of your inventory are now under the asterisk (*) wildcard and reside at the following URL:

http://localhost:9080/inventory/hosts/*

The GET request handler is responsible for handling all GET requests that are made to the target URL. This method responds with a JSON that contains HATEOAS links.

The UriInfo object is what is used to build your HATEOAS links.

The @Context annotation is a part of CDI and indicates that the UriInfo will be injected when the resource is instantiated.

Your new InventoryResource class is now replaced. Next, let’s implement the getSystems method and build the response JSON object.

InventoryManager.java

 1package io.openliberty.guides.microprofile;
 2
 3import java.util.concurrent.ConcurrentHashMap;
 4import java.util.concurrent.ConcurrentMap;
 5
 6import javax.enterprise.context.ApplicationScoped;
 7import javax.json.Json;
 8import javax.json.JsonArray;
 9import javax.json.JsonArrayBuilder;
10import javax.json.JsonObject;
11import javax.json.JsonObjectBuilder;
12
13import io.openliberty.guides.microprofile.util.ReadyJson;
14import io.openliberty.guides.microprofile.util.InventoryUtil;
15
16@ApplicationScoped
17public class InventoryManager {
18
19    private ConcurrentMap<String, JsonObject> inv = new ConcurrentHashMap<>();
20
21    public JsonObject get(String hostname) {
22        JsonObject properties = inv.get(hostname);
23        if (properties == null) {
24            if (InventoryUtil.responseOk(hostname)) {
25                properties = InventoryUtil.getProperties(hostname);
26                this.add(hostname, properties);
27            } else {
28                return ReadyJson.SERVICE_UNREACHABLE.getJson();
29            }
30        }
31        return properties;
32    }
33
34    public void add(String hostname, JsonObject systemProps) {
35        inv.putIfAbsent(hostname, systemProps);
36    }
37
38    public JsonObject list() {
39        JsonObjectBuilder systems = Json.createObjectBuilder();
40        inv.forEach((host, props) -> {
41            JsonObject systemProps = Json.createObjectBuilder()
42                                         .add("os.name", props.getString("os.name"))
43                                         .add("user.name", props.getString("user.name"))
44                                         .build();
45            systems.add(host, systemProps);
46        });
47        systems.add("hosts", systems);
48        systems.add("total", inv.size());
49        return systems.build();
50    }
51
52    public JsonArray getSystems(String url) {
53        // inventory content
54        JsonObject content = InventoryUtil.buildHostJson("*", url);
55
56        // collecting systems jsons
57        JsonArrayBuilder jsonArray = inv.keySet().stream().map(host -> {
58            return InventoryUtil.buildHostJson(host, url);
59        }).collect(Json::createArrayBuilder, JsonArrayBuilder::add, JsonArrayBuilder::add);
60
61        jsonArray.add(content);
62
63        return jsonArray.build();
64    }
65
66}

Linking to each available resource

Take a look at your InventoryManager and InventoryUtil files.

Replace the InventoryManager class.
src/main/java/io/openliberty/guides/microprofile/InventoryManager.java

InventoryManager.java

 1package io.openliberty.guides.microprofile;
 2
 3import java.util.concurrent.ConcurrentHashMap;
 4import java.util.concurrent.ConcurrentMap;
 5
 6import javax.enterprise.context.ApplicationScoped;
 7import javax.json.Json;
 8import javax.json.JsonArray;
 9import javax.json.JsonArrayBuilder;
10import javax.json.JsonObject;
11import javax.json.JsonObjectBuilder;
12
13import io.openliberty.guides.microprofile.util.ReadyJson;
14import io.openliberty.guides.microprofile.util.InventoryUtil;
15
16@ApplicationScoped
17public class InventoryManager {
18
19    private ConcurrentMap<String, JsonObject> inv = new ConcurrentHashMap<>();
20
21    public JsonObject get(String hostname) {
22        JsonObject properties = inv.get(hostname);
23        if (properties == null) {
24            if (InventoryUtil.responseOk(hostname)) {
25                properties = InventoryUtil.getProperties(hostname);
26                this.add(hostname, properties);
27            } else {
28                return ReadyJson.SERVICE_UNREACHABLE.getJson();
29            }
30        }
31        return properties;
32    }
33
34    public void add(String hostname, JsonObject systemProps) {
35        inv.putIfAbsent(hostname, systemProps);
36    }
37
38    public JsonObject list() {
39        JsonObjectBuilder systems = Json.createObjectBuilder();
40        inv.forEach((host, props) -> {
41            JsonObject systemProps = Json.createObjectBuilder()
42                                         .add("os.name", props.getString("os.name"))
43                                         .add("user.name", props.getString("user.name"))
44                                         .build();
45            systems.add(host, systemProps);
46        });
47        systems.add("hosts", systems);
48        systems.add("total", inv.size());
49        return systems.build();
50    }
51
52    public JsonArray getSystems(String url) {
53        // inventory content
54        JsonObject content = InventoryUtil.buildHostJson("*", url);
55
56        // collecting systems jsons
57        JsonArrayBuilder jsonArray = inv.keySet().stream().map(host -> {
58            return InventoryUtil.buildHostJson(host, url);
59        }).collect(Json::createArrayBuilder, JsonArrayBuilder::add, JsonArrayBuilder::add);
60
61        jsonArray.add(content);
62
63        return jsonArray.build();
64    }
65
66}

The getSystems method accepts a target URL as an argument and returns a JSON object that contains HATEOAS links.

Replace the InventoryUtil class.
src/main/java/io/openliberty/guides/microprofile/util/InventoryUtil.java

InventoryUtil.java

 1package io.openliberty.guides.microprofile.util;
 2
 3import java.net.HttpURLConnection;
 4import java.net.URI;
 5import java.net.URL;
 6
 7import javax.json.Json;
 8import javax.json.JsonArray;
 9import javax.json.JsonArrayBuilder;
10import javax.json.JsonObject;
11import javax.ws.rs.client.Client;
12import javax.ws.rs.client.ClientBuilder;
13import javax.ws.rs.core.MediaType;
14import javax.ws.rs.core.UriBuilder;
15
16import org.apache.commons.lang3.StringUtils;
17
18public class InventoryUtil {
19
20    private static final int PORT = 9080;
21    private static final String PROTOCOL = "http";
22    private static final String SYSTEM_PROPERTIES = "/system/properties";
23
24    public static JsonObject getProperties(String hostname) {
25        Client client = ClientBuilder.newClient();
26        URI propURI = InventoryUtil.buildUri(hostname);
27        return client.target(propURI)
28                     .request(MediaType.APPLICATION_JSON)
29                     .get(JsonObject.class);
30    }
31
32    public static JsonObject buildHostJson(String hostname, String url) {
33        return Json.createObjectBuilder()
34                   .add("hostname", hostname)
35                   .add("_links", InventoryUtil.buildLinksForHost(hostname, url))
36                   .build();
37    }
38
39    public static JsonArray buildLinksForHost(String hostname, String invUri) {
40
41        JsonArrayBuilder links = Json.createArrayBuilder();
42
43        links.add(Json.createObjectBuilder()
44                      .add("href", StringUtils.appendIfMissing(invUri, "/") + hostname)
45                      .add("rel", "self"));
46
47        links.add(Json.createObjectBuilder()
48                .add("href", InventoryUtil.buildUri(hostname).toString())
49                .add("rel", "properties"));
50
51        return links.build();
52    }
53
54    public static boolean responseOk(String hostname) {
55        try {
56            URL target = new URL(buildUri(hostname).toString());
57            HttpURLConnection http = (HttpURLConnection) target.openConnection();
58            http.setConnectTimeout(50);
59            int response = http.getResponseCode();
60            return (response != 200) ? false : true;
61        } catch (Exception e) {
62            return false;
63        }
64    }
65
66    private static URI buildUri(String hostname) {
67        return UriBuilder.fromUri(SYSTEM_PROPERTIES)
68                .host(hostname)
69                .port(PORT)
70                .scheme(PROTOCOL)
71                .build();
72    }
73
74}

The buildHostJson helper method builds in the InventoryUtil class. It creates a JSON object that contains the hostname of your system and the _links array, which is generated separately in the buildLinksForHost helper method.

This helper accepts a hostname and a target URL as arguments. The helper builds a link that points to the inventory entry with a self relationship and also builds a link that points to the system service with a properties relationship:

  • http://localhost:9080/inventory/hosts/<hostname>

  • http://<hostname>:9080/system/properties

Linking to inactive services or unavailable resources

InventoryUtil.java

 1package io.openliberty.guides.microprofile.util;
 2
 3import java.net.HttpURLConnection;
 4import java.net.URI;
 5import java.net.URL;
 6
 7import javax.json.Json;
 8import javax.json.JsonArray;
 9import javax.json.JsonArrayBuilder;
10import javax.json.JsonObject;
11import javax.ws.rs.client.Client;
12import javax.ws.rs.client.ClientBuilder;
13import javax.ws.rs.core.MediaType;
14import javax.ws.rs.core.UriBuilder;
15
16import org.apache.commons.lang3.StringUtils;
17
18public class InventoryUtil {
19
20    private static final int PORT = 9080;
21    private static final String PROTOCOL = "http";
22    private static final String SYSTEM_PROPERTIES = "/system/properties";
23
24    public static JsonObject getProperties(String hostname) {
25        Client client = ClientBuilder.newClient();
26        URI propURI = InventoryUtil.buildUri(hostname);
27        return client.target(propURI)
28                     .request(MediaType.APPLICATION_JSON)
29                     .get(JsonObject.class);
30    }
31
32    public static JsonObject buildHostJson(String hostname, String url) {
33        return Json.createObjectBuilder()
34                   .add("hostname", hostname)
35                   .add("_links", InventoryUtil.buildLinksForHost(hostname, url))
36                   .build();
37    }
38
39    public static JsonArray buildLinksForHost(String hostname, String invUri) {
40
41        JsonArrayBuilder links = Json.createArrayBuilder();
42
43        links.add(Json.createObjectBuilder()
44                      .add("href", StringUtils.appendIfMissing(invUri, "/") + hostname)
45                      .add("rel", "self"));
46
47        links.add(Json.createObjectBuilder()
48                .add("href", InventoryUtil.buildUri(hostname).toString())
49                .add("rel", "properties"));
50
51        return links.build();
52    }
53
54    public static boolean responseOk(String hostname) {
55        try {
56            URL target = new URL(buildUri(hostname).toString());
57            HttpURLConnection http = (HttpURLConnection) target.openConnection();
58            http.setConnectTimeout(50);
59            int response = http.getResponseCode();
60            return (response != 200) ? false : true;
61        } catch (Exception e) {
62            return false;
63        }
64    }
65
66    private static URI buildUri(String hostname) {
67        return UriBuilder.fromUri(SYSTEM_PROPERTIES)
68                .host(hostname)
69                .port(PORT)
70                .scheme(PROTOCOL)
71                .build();
72    }
73
74}

Consider what happens when one of the return links does not work or when a link should be available for one object but not for another. In other words, it is important that a resource or service is available and running before it is linked in the _links array.

Although this guide does not cover this case, always make sure that you receive a good response code from a service before you link that service. Similarly, make sure that it makes sense for a particular object to access a resource it is linked to. For instance, it doesn’t make sense for an account holder to be able to withdraw money from their account when their balance is 0. Hence, the account holder should not be linked to a resource that provides money withdrawal.

Building and running the application

To build the application, run the Maven install phase from the command line in the start directory:

mvn install

This command builds the application and creates a .war file in the target directory. It also configures and installs Open Liberty into the target/liberty/wlp directory.

Next, run the Maven liberty:start-server goal:

mvn liberty:start-server

This goal starts an Open Liberty server instance. Your Maven pom.xml is already configured to start the application in this server instance.

After the server runs, you can find your new hypermedia-driven inventory service at the following URL:

Testing the hypermedia-driven RESTful web service

At the following URLs, access the inventory service that is now driven by hypermedia:

The first URL returns the current contents of the inventory, and the second URL returns the system properties for the host name. If the inventory does not contain an entry for the host name that is specified in the URL, the system service that is running on the requested host name is called instead. The system properties are retrieved from that system service and then stored in the inventory and returned.

If the servers are running, you can point your browser to each of the previous URLs to test the application manually. Nevertheless, you should rely on automated tests since they are more reliable and trigger a failure if a change introduces a defect.

Setting up your tests

EndpointTest.java

  1package it.io.openliberty.guides.hateoas;
  2
  3import static org.junit.Assert.assertEquals;
  4
  5import org.junit.After;
  6import org.junit.Before;
  7import org.junit.Test;
  8
  9import javax.json.JsonArray;
 10import javax.ws.rs.client.Client;
 11import javax.ws.rs.client.ClientBuilder;
 12import javax.ws.rs.core.Response;
 13
 14import org.apache.cxf.jaxrs.provider.jsrjsonp.JsrJsonpProvider;
 15
 16public class EndpointTest {
 17    private String port;
 18    private String baseUrl;
 19
 20    private Client client;
 21
 22    private final String SYSTEM_PROPERTIES = "system/properties";
 23    private final String INVENTORY_HOSTS = "inventory/hosts";
 24
 25    @Before
 26    public void setup() {
 27        port = System.getProperty("liberty.test.port");
 28        baseUrl = "http://localhost:" + port + "/";
 29
 30        client = ClientBuilder.newClient();
 31        client.register(JsrJsonpProvider.class);
 32    }
 33
 34    @After
 35    public void teardown() {
 36        client.close();
 37    }
 38
 39    @Test
 40    public void testSuite() {
 41        this.testLinkForInventoryContents();
 42        this.testLinksForSystem();
 43    }
 44
 45    /**
 46     * Checks if the HATEOAS link for the inventory contents (hostname=*) is as expected.
 47     */
 48    public void testLinkForInventoryContents() {
 49        Response response = this.getResponse(baseUrl + INVENTORY_HOSTS);
 50        this.assertResponse(baseUrl, response);
 51
 52        JsonArray sysArray = response.readEntity(JsonArray.class);
 53
 54        String expected, actual;
 55
 56        JsonArray links = sysArray.getJsonObject(0).getJsonArray("_links");
 57
 58        expected = baseUrl + INVENTORY_HOSTS + "/*";
 59        actual = links.getJsonObject(0).getString("href");
 60        assertEquals("Incorrect href", expected, actual);
 61
 62        // asserting that rel was correct
 63        expected = "self";
 64        actual = links.getJsonObject(0).getString("rel");
 65        assertEquals("Incorrect rel", expected, actual);
 66
 67        response.close();
 68    }
 69
 70    /**
 71     * Checks that the HATEOAS links, with relationships 'self' and 'properties' for a simple
 72     * localhost system is as expected.
 73     */
 74    public void testLinksForSystem() {
 75        this.visitLocalhost();
 76
 77        Response response = this.getResponse(baseUrl + INVENTORY_HOSTS);
 78        this.assertResponse(baseUrl, response);
 79
 80        JsonArray sysArray = response.readEntity(JsonArray.class);
 81
 82        String expected, actual;
 83
 84        JsonArray links = sysArray.getJsonObject(0).getJsonArray("_links");
 85
 86        // testing the 'self' link
 87
 88        expected = baseUrl + INVENTORY_HOSTS + "/localhost";
 89        actual = links.getJsonObject(0).getString("href");
 90        assertEquals("Incorrect href", expected, actual);
 91
 92        expected = "self";
 93        actual = links.getJsonObject(0).getString("rel");
 94        assertEquals("Incorrect rel", expected, actual);
 95
 96        // testing the 'properties' link
 97
 98        expected = baseUrl + SYSTEM_PROPERTIES;
 99        actual = links.getJsonObject(1).getString("href");
100        assertEquals("Incorrect href", expected, actual);
101
102        expected = "properties";
103        actual = links.getJsonObject(1).getString("rel");
104        assertEquals("Incorrect rel", expected, actual);
105    }
106
107    /**
108     * Returns a Response object for the specified URL.
109     */
110    private Response getResponse(String url) {
111        return client.target(url).request().get();
112    }
113
114    /**
115     * Asserts that the given URL has the correct (200) response code.
116     */
117    private void assertResponse(String url, Response response) {
118        assertEquals("Incorrect response code from " + url, 200, response.getStatus());;
119    }
120
121    /**
122     * Makes a GET request to localhost at the Inventory service.
123     */
124    private void visitLocalhost() {
125        Response response = this.getResponse(baseUrl + SYSTEM_PROPERTIES);
126        this.assertResponse(baseUrl, response);
127        response.close();
128
129        Response targetResponse = client.target(baseUrl + INVENTORY_HOSTS + "/localhost")
130                                        .request()
131                                        .get();
132        targetResponse.close();
133    }
134}
Create the EndpointTest class.
src/test/java/it/io/openliberty/guides/hateoas/EndpointTest.java

You can use the @Before and @After annotations to perform any setup and teardown tasks for each of your individual tests.

Writing the tests

Each test method must be marked with the @Test annotation. Typically, the execution order of test methods is not controlled, but if control is required, you can place methods in a single container test method. This container method is then the only one marked with the @Test annotation. The following testSuite() contains two test methods, which run in the order they appear:

The test testLinkForInventoryContents is responsible for asserting that the correct HATEOAS link is created for the inventory contents.

The getResponse helper method reuses the same line of code for retrieving a response from a specific URL. This technique helps keep your code neat and organized.

The assertResponse method ensures that the response code that you receive is valid (200).

The testLinksForSystem test is responsible for asserting that the correct HATEOAS links are created for the localhost system. This method checks for both the self link that points to the inventory service and the properties link that points to the system service that is running on the localhost system.

Finally, the method visitLocalhost creates a GET request to the system service, registering the localhost system.

Running the tests

If the server is still running from the previous steps, stop it using the Maven liberty:stop-server goal from command line in the start directory:

mvn liberty:stop-server

Then, verify that the tests pass using the Maven verify goal:

mvn verify

It may take some time before build is complete. If the tests pass, you will see a similar output to the following:

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running it.io.openliberty.guides.hateoas.EndpointTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.086 sec - in it.io.openliberty.guides.hateoas.EndpointTest

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

Great work! You’re done!

You’ve just built and tested a hypermedia-driven RESTful web service on top of Open Liberty.

Guide Attribution

Creating a hypermedia-driven RESTful web service by Open Liberty is licensed under CC BY-ND 4.0

Copied to clipboard
Copy code block
Copy file contents
Git clone this repo to get going right away:
git clone https://github.com/OpenLiberty/guide-rest-hateoas.git
Copy github clone command
Copied to clipboard

Nice work! Where to next?

What did you think of this guide?

Extreme Dislike Dislike Like Extreme Like

What could make this guide better?

Raise an issue to share feedback

Create a pull request to contribute to this guide

Need help?

Ask a question on Stack Overflow

Like Open Liberty? Star our repo on GitHub.

Star