gpt4 book ai didi

json-api - 如何使用 JSONAPI 创建一对多关系的子实体

转载 作者:行者123 更新时间:2023-12-02 18:53:48 38 4
gpt4 key购买 nike

我一直在阅读 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"
}
}
]
}

最佳答案

根据JSONAPI's guide on creating resources ,以下资源创建请求看起来与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" }
}
}
}
}

关于json-api - 如何使用 JSONAPI 创建一对多关系的子实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31996405/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com