Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

openapi - Swagger; specify two responses with same code based on optional parameter

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.

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

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}

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?

Edit: the following seems related: https://github.com/OAI/OpenAPI-Specification/issues/270

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

OpenAPI 2.0

OAS2 does not support multiple response schemas per status code. You can only have a single schema, for example, a free-form object (type: object without properties).

OpenAPI 3.0

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'

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.

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


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.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...