如何通过 HATEOAS 链接访问 REST collection 的一个元素?

How to access one element of a REST collection through HATEOAS links?

我正在尝试构建 RESTful 服务的架构,并使用 Java Spring 为所有这些服务构建网关服务。为了实现后者,我需要为其他服务实现一个客户端,这是我和我的同事试图围绕 HATEOAS 原则设计的,通过 spring-hateoas 模块向相关资源提供 links。

假设我在本地主机上有一个服务 运行,侦听 8080 端口,其中 returns 一个 collection 资源,在 /resources 上有一个 GET 操作。例如:

{
  "_embedded" : {
    "resources" : [ {
      "label" : "My first resource!",
      "resourceId" : 3,
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/resources/3"
        },
        "meals" : {
          "href" : "http://localhost:8080/resources",
          "templated" : true
        }
      }
    }, {
      "label" : "Another resource!",
      "resourceId" : 4,
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/resources/4"
        },
        "meals" : {
          "href" : "http://localhost:8080/resources",
          "templated" : true
        }
      }
    } ]
  },
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/resources",
      "templated" : true
    }
  }
}

我正在尝试使用 HATEOAS 客户端,例如 Traverson。如何仅通过关注 HATEOAS links 来关注资源元素?到目前为止,我的解决方案是在我的 collection 上添加一个 link 到 item,例如:

"_links" : {
    "self" : {
      "href" : "http://localhost:8080/resources",
      "templated" : true
    },
    "item" : {
      "href" : "http://localhost:8080/resources/{id}",
      "templated" : true
    }
}

那我就直接把模板里的id换成Traverson,按照结果来就行了。但这是一个好习惯吗?我应该换个方式吗?

简单来说,特拉弗森就是为了找一个link。

在最简单的情况下,每个 link 都有一个唯一的名称 (rel)。通过简单地向 Traverson 的 follow(...) 函数提供 rel 的名称,它将使用正确的 LinkDiscoverer 并导航到该 rel.

的相应 URI

这是一个Hop

由于目标是导航 API,就像在网页上跟随 link 一样,您必须定义跃点链。

对于您的情况,情况稍微复杂一些,因为您嵌入了多个项目。询问 self link 并不简单,因为您可以很容易地在根文档上看到三个。

因此 Traverson 支持 JSON-Path。如果您检查 reference documentation,很容易看出可以提供 JSON-路径表达式来帮助选择您想要的 link。

只要选择的属性是URI,Traverson就会"hop"给它。

注意:当只使用 rels 时,您可以在 follow(...) 中提供多个 rels 作为字符串。当使用其他任何东西时,比如 JSON-Path 表达式或 rel(...),然后使用一个 follow(...) per hop。值得庆幸的是,这并不难理解,因为您将每个跃点放在单独的一行上(同样,请参阅参考文档以获取示例)。