JSON API 问题。包含与关系

Jwa*_*622 2 json ruby-on-rails json-api

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

为了减少 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"
    }
  }]
}
Run Code Online (Sandbox Code Playgroud)

因此,据我所知,关系部分提供了有关文章表和其他表之间关联的基本/稀疏信息。看起来一篇文章属于一位作者并且有很多评论。

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

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

“包容”和“关系”都必须吗?需要这两个部分背后的直觉是什么?

bea*_*uby 6

这个想法是,arelationship中的aresource只是给出链接数据(即唯一标识相关resource\xe2\x80\x93 的基本数据,这些数据是idtype),以便将其保持在最低限度。

\n\n

另一方面,included如果您想发送一些相关的详细信息resources(例如,最大限度地减少 HTTP 请求的数量),则可以使用该部分。请注意,该included部分预计 resources包含与 a primary resource(即在该data部分内)或资源(此约束在规范中included称为)相关的内容。full linkage

\n\n

简而言之,relationshipsa 的部分resource告诉您哪些 resources与给定的 相关resource,而included部分告诉您这些是什么resources

\n\n

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

\n