Swagger; specify two responses with same code based on optional parameter
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.x
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: Older versions of Swagger UI (before v. 3.39.0) do not automatically generate examples for oneOf
and anyOf
schemas. 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: # <--- Workaround for Swagger UI < 3.39.0
foo: bar