我正在考虑使用 JSONAPI 标准来设计我们的 API。该 API 必须能够做的一件事是接受复合文档(多层深)并创建它。根对象拥有服务器此时一无所知的所有后代(“对多”关系),因此客户端不可能提供 id。
规范是否支持这一点,还是客户端必须按顺序对文档中的每个对象发出 http 请求?
来自 http://jsonapi.org/format/#document-compound-documents
复合文档需要“完全链接”,这意味着每个包含的文档 资源必须由至少一个资源标识符对象来标识 在同一个文档中。这些资源标识符对象可以 是主要数据或代表主要数据中包含的资源链接 或包含的资源。全联动的唯一例外 要求是当关系字段本来包含 通过稀疏字段集排除链接数据。
{
"data": [{
"type": "articles",
"id": "1",
"attributes": {
"title": "JSON API paints my bikeshed!"
},
"links": {
"self": "http://example.com/articles/1"
},
"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" }
]
}
}
}],
"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!"
},
"links": {
"self": "http://example.com/comments/5"
}
}, {
"type": "comments",
"id": "12",
"attributes": {
"body": "I like XML better"
},
"links": {
"self": "http://example.com/comments/12"
}
}]
}
虽然这个问题很老了 - JSONAPI 现在有一个用于创建(POST)复杂文档的标准,称为原子。
https://jsonapi.org/ext/atomic/
示例:
{
"atomic:operations": [
{
"op": "add",
"data": {
"type": "authors",
"id": "acb2ebd6-ed30-4877-80ce-52a14d77d470",
"attributes": {
"name": "dgeb"
}
}
},
{
"op": "add",
"data": {
"type": "articles",
"id": "bb3ad581-806f-4237-b748-f2ea0261845c",
"attributes": {
"title": "JSON API paints my bikeshed!"
},
"relationships": {
"author": {
"data": {
"type": "authors",
"id": "acb2ebd6-ed30-4877-80ce-52a14d77d470"
}
}
}
}
}
]
}