2

我正在尝试使用 Spring Boot 实现 HATEOAS Rest Client。

现在,我陷入了需要将 HATEOAS 转换为实际 API URI 的问题。

如果我发布一个客户类型的新对象,例如:

{
    "name": "Frank",
    "address": "http://localhost:8080/address/23"
}

然后我通过对http://localhost:8080/api/customer/1的请求进行检索,HATEOAS 给了我类似的东西

{
    "name": Frank,
    "_links": {
        "address": {
            "href": "http://localhost:8080/api/customer/1/address"
        }
    }
}

是否可以将形式的链接转换为http://localhost:8080/api/customer/1/addressAPI 调用,例如http://localhost:8080/api/address/23

4

1 回答 1

0

如果您说后看到 HATEOS 返回的内容,

GET: http://localhost:8080/api/customer/1

{
"name": Frank,
"_links": {
    "address": {
        "href": "http://localhost:8080/api/customer/1/address"
    }
  }
}

根据 了解 HATEOS

It's possible to build more complex relationships. With HATEOAS, the output makes it
easy to glean how to interact with the service without looking up a specification or 
other external document

意思是,

在您收到资源详细信息后

http://localhost:8080/api/customer/1 接收到的资源还可以进行哪些其他操作,这些操作将显示为更容易/点击访问您的服务/应用程序,

在这种情况下,HATEOS 可以找到一个http://localhost:8080/api/customer/1/address可以访问的链接,一旦您拥有该链接,customer/1如果您愿意,可以从那里访问,而无需前往任何其他地方customer/1的地址/customer/1/address

同样,如果您有详细/customer/1信息occupation,则链接下方将有另一个address链接http://localhost:8080/api/customer/1/occupation

因此,如果address依赖于customerie 就不可能没有addresscustomer那么您的 API 端点必须是/api/customer/1/address而不是直接/api/address/23的。

但是,在了解了 HATEOS 此类响应背后的这些标准和逻辑之后,如果您仍然想使用自己的链接,这些链接可能与您可以使用的 HATEOS 逻辑不一致,

LinkBuilderHATEOS 接口提供的链接对象。

示例:使用以下类型的对象Customer

Customer c = new Customer( /*parameters*/ );

Link link= linkTo(AnyController.class).slash("address").slash(addressId);
    customer.add(link); 

//considering you want to add link `http://localhost:8080/api/address/23` and `23 is your addressID`.

您也可以创建一个链接列表并继续向该列表中添加许多此类链接,然后将该列表添加到您的对象中。

希望这对你有帮助!

于 2018-08-08T07:04:59.403 回答