rest - Restful Uri结构获取相同类型的资源数组,响应中只有有限的字段?
问题描述
我们有以下 API 来获取我们数据库中所有汽车版本的列表。特定版本可以有多种颜色可供选择。
GET /api/versions/
[
{
"id": 1,
"colors": [{"name":"red", "hex": "#ff0000"},{{"name":"blue", "hex": #0000ff}}], //array of colors of that version
"price": 10000
},
{
"id": 2,
"colors": [{"name":"red", "hex": "#ff0000"},{{"name":"blue", "hex": #0000ff}}], //array of colors of that version
"price": 20000
},
...
]
客户端想要一个 API 来获取不是所有的,而是多个版本的数据,并且只获取颜色字段。这种要求的 URI 应该是什么?我想到了类似下面的东西,但我不确定:
要获取版本 id 8 和 9 的颜色:
GET /api/versions/?fields=colors&id=8,9
[
{
"id": 8,
"colors": [{"name":"tui", "hex": "#gg0000"},{{"name":"rie", "hex": #or0000}}], //array of colors of that version
},
{
"id": 9,
"colors": [{"name":"rie", "hex": "#or0000"},{{"name":"tui", "hex": #gg0000}}], //array of colors of that version
}
]
请注意:我在这里过于简单化了。版本响应非常复杂,除了上面提到的 id、colors 和 price 之外,还包含更多字段。另外,我们将获得多个这样的要求,例如我们目前对颜色的要求,即获得多个版本的价格。
解决方案
您指定的查询参数是完美的!
如果您有汽车的唯一 ID,它可以成为您的 api 端点的一部分,例如
/api/cars/$car_id/versions?fields=colors,price&ids=8,9
或者您可以尝试使用 /api/carversions 而不是 /api/versions。
您也可以参考我对类似问题的回答
推荐阅读
- javascript - 时刻UTC时间如何转换为秒
- python - Python将文件从当前路径移动到与被移动文件类似或相似的特定文件夹
- amazon-web-services - 使用 lambda 目的地时是否需要私有链接
- java - java 8中的内存区方法区、字符串常量池位于哪个内存区?
- 3d - 添加 3D 模型:支持哪些类型的文件?以及在哪里托管 3D 文件?
- typescript - 如何使用 Typescript 在 Codepen 中制作 Vuetify 组件?
- typescript - Typescript 编译器不强制执行相关的泛型
- python - POST 表单提交后下载文件
- java - 是否可以以编程方式滚动到 appbarlayout 的子级?
- excel - 将 .Find 结果分配给变量还是直接将其写入单元格?