假设我有两个表,Book 和 Author,其中每本书都有一个作者的外键。 /books/
端点返回系统中存储的所有书籍的列表。现在假设客户端将使用此列表,并按作者对其进行分组。让服务器返回按作者嵌套和分组的数据以便客户端不需要这样做,这是否是 RESTful?请求响应的分组方法是否有标准? (可能类似于 /books/?groupby=author
)
例如:
// flat
[
{'title': 'Harry Potter', 'author': 'JK Rowling'},
{'title': 'Harry Potter 2', 'author': 'JK Rowling'},
{'title': 'Harry Potter 3', 'author': 'JK Rowling'},
{'title': 'Lord of the Rings', 'author': 'J. R. R. Tolkien'},
]
对比
// nested
[
{'author': 'JK Rowling', books:
[
{'title': 'Harry Potter'},
{'title': 'Harry Potter 2'},
{'title': 'Harry Potter 3'},
]
},
{'author': 'J. R. R. Tolkien', books:
[
{'title': 'Lord of the Rings'}
]
}
]
最佳答案
我希望有一个作者资源,其中包含他们所写的每本书的链接或他们所写的所有书籍的集合的链接。无论哪种情况,您的 API 都可以支持查询参数“?embed=books”,该参数会在返回的 JSON 中填充书籍。
GET /authors/23
{
"name": "JK Rowling",
"_links": [
"books": [
"/books/4",
"/books/532"
], ...
]
}
GET /authors/23?embed=books
{
"name": "JK Rowling",
"books": [
{
"title": "Harry Potter",
"author": "/authors/23"
},
{
"title": "Harry Potter 2",
"author": "/authors/23"
},
]
}
顺便说一句,在真实的系统中,一本书应该能够有多个作者。
关于rest - 如何以 REST 方式对响应进行分组以便于客户端使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36164344/