【发布时间】:2016-09-16 07:10:22
【问题描述】:
self 链接和 related 链接的 JSON API 有什么区别?
【问题讨论】:
标签: ruby-on-rails json json-api
self 链接和 related 链接的 JSON API 有什么区别?
【问题讨论】:
标签: ruby-on-rails json json-api
对于我在回复中实际返回的内容,我很难找到一个简单易懂的答案。
对于 JSON API 的示例,它们具有以下 JSON:
{
"links": {
"self": "http://example.com/articles",
"next": "http://example.com/articles?page[offset]=2",
"last": "http://example.com/articles?page[offset]=10"
},
"data": [{
"type": "articles",
"id": "1",
"attributes": {
"title": "JSON API paints my bikeshed!"
},
"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" }
]
}
},
"links": {
"self": "http://example.com/articles/1"
}
}],
"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"
}
}]
}
这里的这一行:
"self": "http://example.com/articles/1/relationships/author"
是“关系链接”
这里的这一行:
"self": "http://example.com/articles/1/relationships/comments"
也是“关系链接”
是的,我知道这很令人困惑,因为另一个叫做related。这些链接的目的是什么?目的是仅管理关系。所以说你做了一个GET /articles/1/relationships/comments 你确实不返回cmets的信息。您只返回资源类型/ID 和其他一些东西的数组,例如元数据和链接。示例:
{
"data": [{
"type": "comments",
"id": "13"
}, {
"type": "comments",
"id": "29"
}],
"links": {
"self": "http://example.com/articles/1/relationships/comments",
"next": "http://example.com/articles/1/relationships/comments?page[offset]=2",
"last": "http://example.com/articles/1/relationships/comments?page[offset]=4"
},
"meta": {
"copyright": "Copyright 2015 Example Corp.",
"authors": [
"Zach Aysan"
]}
}
为什么这很有用?因为有时我们想只是删除关系,而不是资源(评论、作者)本身。例如,如果我们做了一个DELETE /articles/1/relationships/author,它不会从用户表中删除用户,它只会将该用户作为作者删除。要仅删除一些 cmets,我们执行 PATCH /articles/1/relationships/comments 并仅包含我们想要保留的 cmets。但是请记住,如果后端认为这是正确的做法,它可能会删除实际的 cmets。 (既然没有相关文章的 cmets 有什么用?)
另一个链接呢?为什么是/articles/1/author 而不是/people/9?因为文章的作者可能会在请求之间更改,GET /articles/1/author 将始终返回当前作者。这就是为什么我们通常不需要支持PATCH /articles/1/author 之类的东西,因为将更改引导到资源本身通常更有意义/更安全。 PATCH /people/9,例如,如果有人在编辑文章页面上更改了他们的头像。即使管理员更改了文章的作者,PATCH 仍会转到正确的资源。
我知道。这有点乏味,但一旦理解了所有内容,像 Ember Data 这样的东西就应该组合在一起了。
【讨论】: