REST API Discoverability and HATEOAS – REST API可发现性和HATEOAS

最后修改: 2011年 11月 6日

1. Overview


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

本文将重点讨论REST API的可发现性、HATEOAS和由测试驱动的实际场景。

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.

为了理解可发现性,我们需要理解超媒体作为应用状态的引擎(HATEOAS)的约束。REST API的这一约束是关于从超媒体(真正的超文本)上全面发现资源上的行动/转换,作为应用状态的唯一驱动器

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.

在本节中,我们将使用 Junit、rest-assuredHamcrest测试可发现的个别特征。由于REST服务之前已经有了安全保障,每个测试首先需要在消耗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.

当REST服务以无效的HTTP方法被消耗时,响应应该是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:

API还应该帮助客户端发现该特定资源所允许的有效HTTP方法。为此,我们可以在响应中使用Allow HTTP标头:

public void
    // 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.

创建新资源的操作应始终在响应中包括新创建资源的URI。为此,我们可以使用Location HTTP头。

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


public void whenResourceIsCreated_thenUriOfTheNewlyCreatedResourceIsDiscoverable() {
    // When
    Foo newResource = new Foo(randomAlphabetic(6));
    Response createResp = givenAuth().contentType("application/json")
    String uriOfNewResource= createResp.getHeader(HttpHeaders.LOCATION);

    // Then
    Response response = givenAuth().header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)

    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:


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.

幸运的是,创建的URI和GET所有该类型资源的URI是一样的,唯一的区别是POST HTTP方法,这是一个标准做法。

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).

我们已经看到了REST API是如何从根部完全发现的,并且不需要事先了解–这意味着客户端能够通过对根部进行GET来浏览它。接下来,所有的状态变化都是由客户端使用REST API提供的可用和可发现的转换来驱动的(因此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.