如何在与JSONAPI的多对多关系中创建子实体

Dav*_*vid 15 json-api

我一直在阅读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" }
  ]
}
Run Code Online (Sandbox Code Playgroud)

这只是一个糟糕的例子,或者规范是否真的希望您在发出上述请求以将其与总共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" }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

或者更好的是:

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"
      } 
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

Jud*_*eek 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" }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)