Swagger参数多态

Swagger parameter polymorphism

在Swagger中可以定义多种类型的输入参数吗?

示例: 我有 API 使用 URL http://localhost/tasks/{taskId} 寻址资源。但是每个任务都包含整数 id 和字符串 uuid。我想允许用户通过 id 或 uuid 来寻址资源 - 所以 http://localhost/tasks/123http://localhost/tasks/51f12dbc-02e7-41a6-ab81-2381caea0176 URLs 都是有效的。

但是,关于 swagger 文档 (https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#parameter-object) 参数对象只能有单一类型

Type: Required. The type of the parameter. Since the parameter is not located at the request body, it is limited to simple types (that is, not an object). The value MUST be one of "string", "number", "integer", "boolean", "array" or "file".

那么如何将输入路径参数描述为string/integer?

无法在 Swagger 规范中定义属于多种类型的参数。

在你的情况下,我认为你可以使用字符串来解决问题,它可以在路径参数和服务器应该正确接收数据。

这在 OpenAPI 3.0 中是可能的,使用 oneOf:

openapi: 3.0.0
...
paths:
  /tasks/{taskId}:
    parameters:
      - in: path
        name: taskId
        required: true
        schema:
          oneOf:
            - type: integer
              example: 123
            - type: string
              format: uuid
              example: 51f12dbc-02e7-41a6-ab81-2381caea0176