0

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

客户端使用 application/vnd.api+json 发送 Accept 标头,因此我使用JSON:API格式的资源进行回复。

例如,给出了下表:

  • 作者
  • 文章

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

我的目标是:

获取/作者

返回具有定义数量的作者(资源对象)文章(关系资源对象)的作者(资源对象) - 例如他写的前 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 格式限制/分页相关资源的正确方法是什么?

4

1 回答 1

1

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

除此之外,我注意到您的回复不是对 JSON:API 的抱怨。对于资源链接,必须使用资源标识符对象(has-one)或资源标识符对象列表(has-many)。

您正在使用完整的资源对象。区别在于attributeslinks键。可以使用复合文档将链接的资源对象包含在响应中。

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

于 2019-09-24T11:48:29.713 回答