【问题标题】:JSON API questions. Included vs relationshipsJSON API 问题。包含与关系
【发布时间】:2016-06-29 17:58:03
【问题描述】:

在构建 API 端点之前,我正在阅读 this。我读到了这个关于复合文档的引用:

为了减少 HTTP 请求的数量,服务器可以允许响应 包括相关资源以及请求的主要资源 资源。此类响应称为“复合文档”。

以下是使用 JSON API 规范的示例 JSON 响应:

{
  "data": [{
    "type": "articles",
    "id": "1",
    "attributes": {
      "title": "JSON API paints my bikeshed!"
    },
    "links": {
      "self": "http://example.com/articles/1"
    },
    "relationships": {
      "author": {
        "links": {
          "self": "http://example.com/articles/1/relationships/author",
          "related": "http://example.com/articles/1/author"
        },
        "data": { "type": "people", "id": "9" }
      },
      "comments": {
        "links": {
          "self": "http://example.com/articles/1/relationships/comments",
          "related": "http://example.com/articles/1/comments"
        },
        "data": [
          { "type": "comments", "id": "5" },
          { "type": "comments", "id": "12" }
        ]
      }
    }
  }],
  "included": [{
    "type": "people",
    "id": "9",
    "attributes": {
      "first-name": "Dan",
      "last-name": "Gebhardt",
      "twitter": "dgeb"
    },
    "links": {
      "self": "http://example.com/people/9"
    }
  }, {
    "type": "comments",
    "id": "5",
    "attributes": {
      "body": "First!"
    },
    "relationships": {
      "author": {
        "data": { "type": "people", "id": "2" }
      }
    },
    "links": {
      "self": "http://example.com/comments/5"
    }
  }, {
    "type": "comments",
    "id": "12",
    "attributes": {
      "body": "I like XML better"
    },
    "relationships": {
      "author": {
        "data": { "type": "people", "id": "9" }
      }
    },
    "links": {
      "self": "http://example.com/comments/12"
    }
  }]
}

因此,据我所知,关系部分提供了有关文章表与其他表之间关联的基本/稀疏信息。它看起来像是一篇文章属于_一位作者并拥有_许多 cmets。

链接的用途是什么? API 是否必须使用该链接才能接收有关该关系的更详细的 JSON?这不需要额外的 API 调用吗?这效率高吗?

“包含”部分似乎包含有关关系/关联的更详细信息?

“包含”和“关系”都需要吗?需要这两个部分的直觉是什么?

【问题讨论】:

    标签: ruby-on-rails json json-api


    【解决方案1】:

    这个想法是 resource 中的 relationship 简单地给出链接数据(这是唯一标识相关 resource 的基本数据 - 这些数据是 idtype),按顺序尽量减少。

    另一方面,included 部分在这里,以防您想发送有关某些相关resources 的详细信息(例如,最大限度地减少 HTTP 请求的数量)。请注意,included 部分应包含与primary resource(即在data 部分中)或included 资源(此约束)相关的resources在规范中称为full linkage)。

    简单地说,resourcerelationships 部分告诉你哪些 resources 与给定的resource 相关,included 部分告诉你 resources 是什么

    就链接而言,当您有has_many 关系时,它们可能会派上用场,其链接数据本身可能包含数千条id/type 记录,从而使您的响应文档相当大的。如果您的客户在请求基本resource 时不一定需要这些,您可以决定通过link 提供它们。

    【讨论】:

    • 这里最糟糕的是...进行多个需要时间的 API 调用还是一个巨大的 JSON 数据?
    • 这真的取决于你的具体用例。当你查询一个资源时,你需要一些相关的资源吗?如果是这样,包括他们,打几个电话是没有意义的。
    • 还请注意,您可以对关系使用分页,例如,如果您要复制 Facebook,您只会返回最后的 n 帖子以及用户个人资料,从而使其余可通过链接获得。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-28
    • 1970-01-01
    • 2021-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多