In the 9 years of running Baeldung, we've never been through anything like this pandemic

And, if making my courses more affordable for a while is going to help you stay in business, land a new job, make rent or be able to provide for your family - then it's well worth doing.

Effective immediately, all Baeldung courses are 33% off their normal prices!

You'll find all three courses in the menu, above.

In the 9 years of running Baeldung, we've never been through anything like this pandemic

And, if making my courses more affordable for a while is going to help you stay in business, land a new job, make rent or be able to provide for your family - then it's well worth doing.

Effective immediately, all Baeldung courses are 33% off their normal prices!

You'll find all three courses in the menu, above.

1. Overview

This article will focus on Discoverability of the REST API, HATEOAS and practical scenarios driven by tests.

2. Why Make the API Discoverable

Discoverability of an API is a topic that doesn't get enough well-deserved attention. As a consequence, very few APIs get it right. It's also something that, if done correctly, can make the API not only RESTful and usable but also elegant.

To understand discoverability, we need to understand the Hypermedia As The Engine Of Application State (HATEOAS) constraint. This constraint of a REST API is about full discoverability of actions/transitions on a Resource from Hypermedia (Hypertext really), as the only driver of application state.

If the interaction is to be driven by the API through the conversation itself, concretely via Hypertext, then there can be no documentation. That would coerce the client to make assumptions that are in fact outside of the context of the API.

In conclusion, the server should be descriptive enough to instruct the client how to use the API via Hypertext only. In the case of an HTTP conversation, we could achieve this through the Link header.

3. Discoverability Scenarios (Driven by Tests)

So what does it mean for a REST service to be discoverable?

Throughout this section, we'll test individual traits of discoverability using Junit, rest-assured and Hamcrest. Since the REST Service has been previously secured, each test first needs to authenticate before consuming the API.

3.1. Discover the Valid HTTP Methods

When a REST Service is consumed with an invalid HTTP method, the response should be a 405 METHOD NOT ALLOWED.

The API should also help the client discover the valid HTTP methods that are allowed for that particular Resource. For this, we can use the Allow HTTP Header in the response:

@Test public void whenInvalidPOSTIsSentToValidURIOfResource_thenAllowHeaderListsTheAllowedActions(){ // Given String uriOfExistingResource = restTemplate.createResource(); // When Response res = givenAuth().post(uriOfExistingResource); // Then String allowHeader = res.getHeader(HttpHeaders.ALLOW); assertThat( allowHeader, AnyOf.anyOf( containsString("GET"), containsString("PUT"), containsString("DELETE") ) ); }

3.2. Discover the URI of Newly Created Resource

The operation of creating a new Resource should always include the URI of the newly created resource in the response. For this, we can use the Location HTTP Header.

Now, if the client does a GET on that URI, the resource should be available:

@Test public void whenResourceIsCreated_thenUriOfTheNewlyCreatedResourceIsDiscoverable() { // When Foo newResource = new Foo(randomAlphabetic(6)); Response createResp = givenAuth().contentType("application/json") .body(unpersistedResource).post(getFooURL()); String uriOfNewResource= createResp.getHeader(HttpHeaders.LOCATION); // Then Response response = givenAuth().header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE) .get(uriOfNewResource); Foo resourceFromServer = response.body().as(Foo.class); assertThat(newResource, equalTo(resourceFromServer)); }

The test follows a simple scenario: creating a new Foo resource, then using the HTTP response to discover the URI where the Resource is now available. It also then does a GET on that URI to retrieve the resource and compares it to the original. This is to make sure that it was correctly saved.

3.3. Discover the URI to GET All Resources of That Type

When we GET any particular Foo resource, we should be able to discover what we can do next: we can list all the available Foo resources. Thus, the operation of retrieving a resource should always include in its response the URI where to get all the resources of that type.

For this, we can again make use of the Link header:

@Test public void whenResourceIsRetrieved_thenUriToGetAllResourcesIsDiscoverable() { // Given String uriOfExistingResource = createAsUri(); // When Response getResponse = givenAuth().get(uriOfExistingResource); // Then String uriToAllResources = HTTPLinkHeaderUtil .extractURIByRel(getResponse.getHeader("Link"), "collection"); Response getAllResponse = givenAuth().get(uriToAllResources); assertThat(getAllResponse.getStatusCode(), is(200)); }

Note that the full low-level code for extractURIByRel – responsible for extracting the URIs by rel relation is shown here.

This test covers the thorny subject of Link Relations in REST: the URI to retrieve all resources uses the rel=”collection” semantics.

This type of link relation has not yet been standardized, but is already in use by several microformats and proposed for standardization. Usage of non-standard link relations opens up the discussion about microformats and richer semantics in RESTful web services.

4. Other Potential Discoverable URIs and Microformats

Other URIs could potentially be discovered via the Link header, but there is only so much the existing types of link relations allow without moving to a richer semantic markup such as defining custom link relations, the Atom Publishing Protocol or microformats, which will be the topic of another article.

For example, the client should be able to discover the URI to create new Resources when doing a GET on a specific Resource. Unfortunately, there is no link relation to model create semantics.

Luckily it's a standard practice that the URI for creation is the same as the URI to GET all resources of that type, with the only difference being the POST HTTP method.

5. Conclusion

We've seen how a REST API is fully discoverable from the root and with no prior knowledge – meaning the client is able to navigate it by doing a GET on the root. Moving forward, all state changes are driven by the client using the available and discoverable transitions that the REST API provides in representations (hence Representational State Transfer).

This article covered the some of the traits of discoverability in the context of a REST web service, discussing HTTP method discovery, the relation between create and get, discovery of the URI to get all resources, etc.

The implementation of all these examples and code snippets is available over on GitHub. This is a Maven-based project, so it should be easy to import and run as it is.