Restful Uri结构获取相同类型的资源数组,只有有限的字段作为响应?

时间:2018-05-23 17:52:47

标签: rest api

我们有以下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获取NOT ALL但多个版本数据,并且仅获取颜色字段。这个要求的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,颜色和价格之外还包含更多字段。此外,我们将获得多个此类要求,例如我们目前的颜色,即获得多个版本的价格。

1 个答案:

答案 0 :(得分:0)

您指定的查询参数非常完美!

如果您拥有可以成为api端点一部分的汽车的唯一ID,例如

/api/cars/$car_id/versions?fields=colors,price&ids=8,9

或者您可以尝试使用/ api / carversions而不是/ api / versions。

您也可以将我的答案推荐给similar question