0

我有一个与其他资源(例如评论)有一对多关系的资源(例如帖子)。我不需要相关资源的任何字段,只需要它们的自链接(按需异步获取它们)。响应应如下所示:

{
  "links": {
    "self": "http://example.com/posts/1?xxx",
  },
  "data": [{
    "type": "posts",
    "id": "1",
    "attributes": {
      "title": "JSON API paints my bikeshed!"
    },
    "relationships": {
      "comments": {
        "links": {
          "self": "http://example.com/posts/1/relationships/comments",
          "related": "http://example.com/posts/1/comments"
        },
        "data": [
          { "type": "comments", "id": "5" },
          { "type": "comments", "id": "12" }
        ]
      }
    },
    "links": {
      "self": "http://example.com/posts/1"
    }
  }],
  "included": [{
    "type": "comments",
    "id": "5",
    "links": {
      "self": "http://example.com/comments/5"
    }
  }, {
    "type": "comments",
    "id": "12",
    "links": {
      "self": "http://example.com/comments/12"
    }
  }]
}

我的问题是请求的 URL 应该是什么样子?

我的想法是包含评论,然后使用一个空的稀疏字段集来避免获得任何评论字段,而只是获得自我链接(+id,类型)。因此,它应该看起来像http://example.com/posts/1?include=comments&fields[comments]=[]. 所以我需要一个空的稀疏字段集。

JSON API 规范对稀疏字段集 ( http://jsonapi.org/format/#fetching-sparse-fieldsets ) 及其与链接的关系没有多说。

4

1 回答 1

0

JSON API 能够回答我的问题

简而言之,指定空稀疏字段集的正确方法是:

http://example.com/posts/1?include=comments&fields[comments]=

关于是否在关系对象中包含指向各个关系项的链接的讨论正在进行中:

{
  "links": {
    "self": "http://example.com/posts/1",
  },
  "data": [{
    "type": "posts",
    "id": "1",
    "attributes": {
      "title": "JSON API paints my bikeshed!"
    },
    "relationships": {
      "comments": {
        "links": {
          "self": "http://example.com/posts/1/relationships/comments",
          "related": "http://example.com/posts/1/comments",
          "item": [ "http://example.com/comments/5", "http://example.com/comments/12" ]
        },
        "data": [{
           "type": "comments", 
           "id": "5", 
           "links": {
              "about": "http://example.com/comments/5"
            }
        }, {
           "type": "comments", 
           "id": "12", 
           "links": {
              "about": "http://example.com/comments/12"
            }
        }] 
      }
    },
    "links": {
      "self": "http://example.com/posts/1"
    }
  }]
}
于 2015-06-22T07:19:03.833 回答