16

我一直在阅读 jsonapi 的文档,但我无法理解这是如何实用的。根据向文章添加评论的文档,评论必须已经存在。

POST /articles/1/relationships/comments HTTP/1.1
Content-Type: application/vnd.api+json
Accept: application/vnd.api+json

{
  "data": [
    { "type": "comments", "id": "123" }
  ]
}

这只是一个糟糕的例子,还是规范真的希望您在发出上述请求以将其关联到总共 2 个请求之前发出创建与实体无关的评论的请求?

您似乎更有可能希望发出这样的请求:

POST /comments HTTP/1.1
Content-Type: application/vnd.api+json
Accept: application/vnd.api+json

{
  "data": {
    "type": "comments",
    "attributes": {
      "body": "blah blah blah"
    },
    "relationships": {
      "article": {
        "data": { "type": "articles", "id": "45" }
      }
    }
  }
}

或者更好:

POST /articles/45/relationships/comments HTTP/1.1
Content-Type: application/vnd.api+json
Accept: application/vnd.api+json

{
  "data": [
    { 
      "type": "comments", 
      "attributes": {
        "body": "blah blah blah"
      } 
    }
  ]
}
4

2 回答 2

2

根据JSONAPI 关于创建资源的指南,以下与 OP 的第一个建议非常相似的资源创建请求是有效请求。

POST /photos HTTP/1.1
Content-Type: application/vnd.api+json
Accept: application/vnd.api+json

{
  "data": {
    "type": "photos",
    "attributes": {
      "title": "Ember Hamster",
      "src": "http://example.com/images/productivity.png"
    },
    "relationships": {
      "photographer": {
        "data": { "type": "people", "id": "9" }
      }
    }
  }
}
于 2016-01-16T00:16:41.737 回答
0

是的,这是一个糟糕的例子——它列在“更新多关系”部分下,并假设评论已经存在。在现实生活中,你的第二个例子会很好。

有一个客户端生成的id 与数据一起传递的概念,但假设客户端能够生成全局唯一的 id,在评论的情况下,客户端肯定不是。

服务器可以接受客户端生成的 ID 以及创建资源的请求。必须使用 id 键指定 ID,其值必须是通用唯一标识符。客户端应该使用 RFC 4122 [RFC4122] 中描述的正确生成和格式化的 UUID。

于 2016-01-16T06:49:39.700 回答