【问题标题】:How to specify path like /pets/{id} but with multiple ids?如何指定 /pets/{id} 之类的路径但具有多个 ID?
【发布时间】:2025-12-14 05:50:02
【问题描述】:

我想创建一个可以接受任意数量的以逗号分隔的 ID 的路径。它应该接受以下所有内容:

GET /pets/1,2  # returns info about pets with ids 1, 2
GET /pets/4,10,12,124,2  # same, for pets with ids 4, 10, 12, 124, 2

“构建你不会讨厌的 API”这本书给了我这个想法。 我如何大摇大摆地做到这一点?

【问题讨论】:

  • 请添加更多详细信息,说明您想要实现的目标。为什么需要多个 id?
  • @CássioMazzochiMolin 获取有关多个对象的信息。见编辑。
  • 使用查询参数并重复一遍:GET /pets/id=4&id=10&id=12&id=124&id=2
  • 相关问题(但不是具体的):*.com/questions/4541338/….
  • @CássioMazzochiMolin 看起来不太整齐

标签: api rest swagger


【解决方案1】:

Swagger 2.0 支持collectionFormat 参数。来自documentation

如果使用array 类型,则确定数组的格式。可能的值是:

  • csv:逗号分隔值:foo,bar
  • ssv:空格分隔值:foo bar
  • tsv:制表符分隔值:foo\tbar
  • pipes:管道分隔值:foo|bar
  • multi:对应多个参数实例,而不是单个实例foo=bar&foo=baz的多个值。这仅对“query”或“formData”中的参数有效。

默认值为csv

使用示例见documentation

{
  "get": {
    "description": "Returns pets based on ID",
    "summary": "Find pets by ID",
    "operationId": "getPetsById",
    "produces": [
      "application/json",
      "text/html"
    ],
    "responses": { ... }
  },
  "parameters": [
    {
      "name": "id",
      "in": "path",
      "description": "ID of pet to use",
      "required": true,
      "type": "array",
      "items": {
        "type": "string"
      },
      "collectionFormat": "csv"
    }
  ]
}

【讨论】:

  • 这是否会将不带任何逗号的 /pets/123 捕获为具有 1 个元素的数组?
最近更新 更多