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

最后修改: 2011年 11月 6日

1. Overview

1.概述

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

2.为什么要使API可被发现

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.

API的可发现性是一个没有得到足够重视的话题。因此,很少有API能做到这一点。如果做得正确的话,这也是可以使API不仅是RESTful和可用的,而且是优雅的。

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.

如果交互是由API通过对话本身驱动的,具体来说是通过超文本,那么就不能有文档。这将迫使客户做出实际上是在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.

总之,服务器应该有足够的描述性,只通过超文本指示客户如何使用API。在HTTP对话的情况下,我们可以通过Link头来实现这一点。

3. Discoverability Scenarios (Driven by Tests)

3.可发现性方案(由测试驱动)

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

那么,REST服务的可发现性是什么意思?

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

3.1.发现有效的HTTP方法

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标头:

@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

3.2.发现新创建资源的URI

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:

现在,如果客户对该URI进行GET操作,该资源应该是可用的。

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

该测试遵循一个简单的场景:创建一个新的Foo资源,然后使用HTTP响应来发现该资源现在可用的URI。然后对该URI进行GET,以检索该资源,并将其与原始资源进行比较。这是为了确保它被正确保存。

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

3.3.发现URI来获取该类型的所有资源

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.

当我们获取任何特定的Foo资源时,我们应该能够发现我们接下来可以做什么:我们可以列出所有可用的Foo资源。因此,检索资源的操作应该总是在其响应中包括获取该类型所有资源的URI。

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

为此,我们可以再次利用Link标头。

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

请注意,extractURIByRel的全部底层代码–负责通过rel关系来提取URI

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

这个测试涵盖了REST中链接关系的棘手问题:检索所有资源的URI使用rel=”collection”语义。

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.

这种类型的链接关系尚未被标准化,但已经被几个微格式所使用,并提议进行标准化。非标准链接关系的使用开启了关于微格式和RESTful网络服务中更丰富语义的讨论。

4. Other Potential Discoverable URIs and Microformats

4.其他潜在的可发现URI和微格式

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.

其他URI有可能通过Link头发现,但是如果不转向更丰富的语义标记,如定义自定义链接关系原子发布协议微格式,这将是另外一篇文章的主题。

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.

例如,当对特定资源进行GET时,客户端应该能够发现URI来创建新的资源。不幸的是,没有与create语义模型的链接关系。

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

5.结论

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.

这篇文章涵盖了REST网络服务背景下可发现性的一些特征,讨论了HTTP方法的发现、创建和获取之间的关系、发现获取所有资源的URI,等等。

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.

所有这些例子和代码片段的实现都可以在GitHub上获得。这是一个基于Maven的项目,所以应该很容易导入并按原样运行。