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

openapiswaggerswagger-2.0

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

Best Answer

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
Related Topic