【问题标题】:Rest Api - Given the following output, what would be the correct url format? [closed]Rest Api - 给定以下输出,正确的 url 格式是什么? [关闭]
【发布时间】:2018-09-26 05:04:59
【问题描述】:
假设我正在构建一个 rest api,它在给定以下 url 的情况下产生以下输出:
/所有者/123/动物
{
{
业主:123,
动物:猫
},
{
业主:123,
动物:狗
},
{
业主:123,
动物:海象
}
}
什么是让特定所有者拥有的所有动物归还的宁静方式?比如,url 是什么样的?
{
拥有者:123
动物:{猫、老鼠、海象}
}
还是让客户端解析第一个 json 输出会更好?
【问题讨论】:
-
在 URI 中放入什么字符并不重要。因此,给出的任何建议都只是一种意见。更重要的是,URI 被赋予了一个有意义的关系名称(就像在 Web 中,URI 使用人类友好的文本进行注释,赋予链接一些有用的含义)。客户端永远不需要解释 URI 中的段来确定它的意图,客户端也不应该认为 URI(或它指向的资源)到 return a specific type
标签:
java
json
spring
rest
api
【解决方案1】:
考虑到您的 API 客户端在 /owner/123/animal 中添加了 123,我认为他已经知道他在为谁请求动物,因此在响应中添加 owner 字段可能是多余的。
我的建议是在/owner/123/animal URL 处返回动物列表。在 Spring 中,定义如下所示。
@RestController
public class OwnerController {
@GetMapping(value = "owner/{ownerId}/animal")
public List<Animal> getAnimalsForOwner(@PathVariable("ownerId") Long id) {
}
}
示例响应为[ {"name": "First"}, {"name": "Second"} ]
【解决方案2】:
/owner/123/animals
它应该只返回动物列表。
例如
[{name:'cat';age:'6 month'},{name:'dog';age:'8 month'}]
【解决方案3】:
/所有者/123/动物
此网址应返回所有者拥有的 id 为 123 的动物。
我更喜欢使用动物而不是动物。
获取 /owner/123/animals
响应:动物列表
[
{
"name": "Cat",
"color": "Grey"
},
{
"name": "Dog",
"color": "Black"
}
]
您还可以让消费者选择响应数据
GET /owner/123/animals ?包括=名称
回复可以
[
{
"name": "Cat"
},
{
"name": "Dog"
}
]
或
{
"names": "cat,Dog"
}