首页 > 解决方案 > 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 之外,还包含更多字段。另外,我们将获得多个这样的要求,例如我们目前对颜色的要求,即获得多个版本的价格。

标签: restapi

解决方案


您指定的查询参数是完美的!

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

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

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

您也可以参考我对类似问题的回答


推荐阅读