REST API 可發現性和 HATEOAS

REST,Spring
Remote
0
09:06 PM · Dec 01 ,2025

1. 概述

本文將重點介紹 REST API 的可發現性、HATEOAS 以及由測試驅動的實用場景

2. 為什麼使API可發現API的可發現性是一個常常被忽視但卻至關重要的議題。因此,很少有API能夠做到這一點。但如果正確地進行,它不僅能使API具有RESTful的特性和可使用性,還能使其優雅化。

為了理解可發現性,我們需要理解Hypermedia As The Engine Of Application State (HATEOAS)的約束。 這個REST API的約束是關於從Hypermedia(實際上是超文本)中發現資源上的動作/轉換的完全可發現性,作為應用程序狀態的唯一驅動因素。

如果交互應該通過API本身(通過超文本)來驅動,那麼就不能有文檔。這會迫使客户端做出實際上超出API上下文的假設。

總之,服務器應該足夠描述性,以通過超文本指導客户端如何使用API。 在HTTP交互的情況下,我們可以通過Link頭來實現這一點。

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. 其他潛在可發現的URI和Microformat

可以通過Link頭髮現的其他URI

雖然可以通過Link頭髮現其他URI,但現有鏈接關係類型在不轉向更豐富的語義標記,例如 定義自定義鏈接關係, Atom Publishing Protocolmicroformats,但這些標記將是另一篇文章的主題。

例如,客户端應該能夠通過對特定資源執行GET請求來發現創建新資源的URI。不幸的是,沒有鏈接關係來模擬create語義。

幸運的是,創建URI與獲取所有該類型資源的URI相同,唯一的區別是POST HTTP方法。

5. 結論

我們已經看到 REST API 如何從根目錄完全可發現,且無需任何先驗知識 – 這意味着客户端可以通過對根目錄執行 GET 操作來導航它。 展望未來,客户端將使用 REST API 提供且可發現的過渡來驅動所有狀態更改(因此 表示方法轉換)。

本文涵蓋了在 REST Web 服務中可發現性的某些特徵,討論了 HTTP 方法發現、創建和獲取之間的關係、獲取所有資源的 URI 的發現等。

user avatar
0 位用戶收藏了這個故事!
收藏

發佈 評論

Some HTML is okay.