昂首阔步;根据可选参数指定两个具有相同代码的响应昂首阔步、可选、根据、参数

2023-09-07 13:50:10 作者:最痛不过亡心

此问题与 (Swagger - 指定可选对象属性或多重响应),因为该 OP 试图返回 200 或 400.

This question is not a duplicate of (Swagger - Specify Optional Object Property or Multiple Responses) because that OP was trying to return a 200 or a 400.

我有一个带有可选参数的 GET;例如,GET/endpoint?selector=foo.

I have a GET with an optional parameter; e.g., GET /endpoint?selector=foo.

我想返回一个 200,它的架构根据参数是否被传递而不同,例如:

I want to return a 200 whose schema is different based on whether the parameter was passed, e.g.,:

GET /endpoint -> {200, schema_1}
GET /endpoint?selector=blah  -> {200, schema_2}

在 yaml 中,我尝试使用两个 200 代码,但查看器将它们压扁,就好像我只指定了一个一样.

In the yaml, I tried having two 200 codes, but the viewer squashes them down as if I only specified one.

有没有办法做到这一点?

Is there a way to do this?

以下似乎相关:https://github.com/OAI/OpenAPI-规范/问题/270

推荐答案

OpenAPI 2.0

OAS2 不支持每个状态代码的多个响应模式.您只能有一个模式,例如,自由形式的对象(type: object 没有 properties).

在 OAS3 中,您可以使用 oneOf 为同一操作定义多个可能的请求体或响应体:

In OAS3 you can use oneOf to define multiple possible request bodies or response bodies for the same operation:

openapi: 3.0.0
...
paths:
  /path:
    get:
      responses:
        '200':
          description: Success
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: '#/components/schemas/ResponseOne'
                  - $ref: '#/components/schemas/ResponseTwo'

但是,不可能将特定的响应模式映射到特定的参数值.您需要在响应、操作和操作的 description 中口头记录这些细节/或参数.

However, it's not possible to map specific response schemas to specific parameter values. You'll need to document these specifics verbally in the description of the response, operation and/or parameter.

这是一个可能相关的增强请求:允许使用 get-^ post-^ 等重载 operationObject

Here's a possibly related enhancement request: Allow operationObject overloading with get-^ post-^ etc

Swagger UI 用户注意事项:截至撰写本文时(2018 年 12 月),Swagger UI 不会自动为 oneOfanyOf 模式生成示例.您可以关注this issue 获取更新.

Note for Swagger UI users: As of this writing (December 2018) Swagger UI does not automatically generate examples for oneOf and anyOf schemas. You can follow this issue for updates.

作为一种解决方法,您可以手动指定响应 exampleexamples.请注意,使用多个 examples 需要 Swagger UI 3.23.0+ 或 Swagger Editor 3.6.31+.

As a workaround, you can specify a response example or examples manually. Note that using multiple examples require Swagger UI 3.23.0+ or Swagger Editor 3.6.31+.

      responses:
        '200':
          description: Success
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: '#/components/schemas/ResponseOne'
                  - $ref: '#/components/schemas/ResponseTwo'
              example:   # <--------
                foo: bar