JSON:API格式(Content-Typeapplication/vnd.api+json)资源大量关系资源的正确处理方法

Proper way to handle a large amount of relationship resources of a resource in JSON:API format (Content-Type application/vnd.api+json)

我正在构建一个 api 并且正在尝试处理以下问题:

客户端发送application/vnd.api+json的Accept头,所以我用JSON:API格式回复资源。

例如下表:

具有 1:n 关系 - 例如 一位作者写了 100 篇文章

我的目标是:

GET /author

returns 作者(资源对象)具有定义数量的 篇文章(关系资源对象)- 例如他写的前 3 篇文章。

格式为:

{
  "links": {
    "self": "http://example.com/author",
    "next": "http://example.com/author?page[offset]=2",
    "last": "http://example.com/author?page[offset]=10"
  },
  "data": [
    {
      "type": "author",
      "id": "1",
      "attributes": {
        "name": "Arthur"
      },
      "relationships": {
        "article": {
          "count": 100,
          "links": {
            "self": "http://example.com/author/1/relationships/article",
            "related": "http://example.com/author/1/article"
          },
          "data": [
            {
              "type": "article",
              "id": "4",
              "attributes": {
                "title": "1 reason why I should use json:api"
              },
              "links": {
                "self": "http://example.com/article/4"
              }
            },
            {
              "type": "article",
              "id": "7",
              "attributes": {
                "title": "2 reasons why I should use json:api"
              },
              "links": {
                "self": "http://example.com/article/7"
              }
            },
            {
              "type": "article",
              "id": "42",
              "attributes": {
                "title": "3 reasons why I should use json:api"
              },
              "links": {
                "self": "http://example.com/article/42"
              }
            }
          ]
        }
      }
    }
  ]
}

我的想法:

使用像

这样的查询参数
http://example.com/author?relationship[]=article,orderby=date,asc=true,limit=3

tl;博士:

以JSON:API格式获取limit/paginate相关资源的正确方法是什么?

该规范不涉及包含的相关资源的分页和排序。如果您需要对它们进行分页或排序,我建议不要包含相关资源,而是使用关系 link。缺点是有一个额外的请求...

除此之外,我注意到您的回复并不是对 JSON:API 的投诉。对于resource linkage a resource identifier object(has-one)或资源标识符对象列表(has-many)必须使用。

您正在使用完整的资源对象。区别在于 attributeslinks 键。链接的资源对象可以使用 compound document.

包含在响应中

您使用查询参数允许客户端控制相关资源的包含的想法实际上是规范的一部分。因此它使用 include 查询参数。这在规范的 Inclusion of Related Resources 章节中有详细描述。但如前所述,不包括所包含资源的分页和排序。