复合响应的规则?

Rules for Composite Responses?

我已经阅读了很多文章和 Apigee 文档以及从实用角度设计 RESTful API 的最佳实践。不过,我不太了解的一件事是,为 API 的消费者构建可以选择性地在同一文档中包含其他资源的设施是好是坏。

我的直觉是通常要避免以下情况:-

/accounts?include=transactions

{ accounts: [
    { "id": "101",
      ... 
      "transactions": [ ... ]
    },...

是不是更好:-

/accounts

{ accounts: [
    { "id": "101",
      ... 
      "transactions": /link/to/transactions/for/acccount
    },...

然后

/transactions

{ "transactions": [
    { "id": ...

我不介意遵守 REST 的纯粹原则,例如。 HATEOS 等 我持这种观点的主要原因是因为:-

  1. 有选择地将 /transactions 加载到我的 /accounts 意味着这会在提供 API 的服务组件之间引入耦合 - 这与架构无关(单体或微服务)

这是一个公平的论点/方法吗?

您可能还想查看 sidecar embedding

One thing I cannot quite get a feel for though is whether building the facility for consumers of the API to optionally include other resources in the same document is good or bad.

嗯,可能两者都不是。它可能适合或不适合您的用例,但在正确的设置下可能会出现相反的情况。

就是说,如果您从 REST 的角度考虑问题,那么查看参考实现 (WWW) 的功能不会有什么坏处。网络上占主导地位的超媒体类型是 HTML;你有表示,links 到辅助表示,但绝对没有 "here is a representation of something this document links to, just in case".

的模拟

换句话说,"link to everything and let the caches sort it out" 有一个既定的、非常成功的先例。菲尔丁自己 wrote

Query results are represented by a list of links with summary information, not by arrays of object representations (query is not a substitute for identification of resources).

另一种妥协是支持两种资源;带有 links 的配对向下版本,以及带有嵌入式数据的丰富版本。 GetEventStore 有这种模式,具有三种不同的资源

http://127.0.0.1:2113/streams/newstream2
vs
http://127.0.0.1:2113/streams/newstream2?embed=rich
vs
http://127.0.0.1:2113/streams/newstream2?embed=body

您可以向两种代表出示 links,让您的客户选择最适合他们情况的一种;或者(如果您使用的是 HATEOAS),您可以控制哪些 link 关系出现在哪些表示中。

(另一种可能性是有一个资源,但每个表示都有一个单独的媒体类型)。

您可能还需要考虑 "aggregate" 资源——负责对域模型进行修改——可能不同于许多支持查询但不支持修改的 "projection" 资源。这就是 CQRS 方法。

吉姆·韦伯:"You should expect to have many many more resources in your integration domain than you do business objects in your business domain."