How to define different responses for same HTTP status code in OpenAPI (Swagger)?
This is possible in OpenAPI 3.0 but not in 2.0.
OpenAPI 3.0 supports oneOf
for specifying alternate schemas for the response. You can also add multiple response examples
, such as successful and failed responses. Swagger UI supports multiple examples
since v. 3.23.0.
openapi: 3.0.0
...
paths:
/something:
get:
responses:
'200':
description: Result
content:
application/json:
schema:
oneOf:
- $ref: '#/components/schemas/ApiResultOk'
- $ref: '#/components/schemas/ApiResultError'
examples:
success:
summary: Example of a successful response
value:
result: true
token: abcde12345
error:
summary: Example of an error response
value:
result: false
errorCode: "00002"
errorMsg: "duplicated account already exist"
components:
schemas:
ApiResultOk:
type: object
properties:
result:
type: boolean
enum: [true]
token:
type: string
required:
- result
- token
ApiResultError:
type: object
properties:
result:
type: boolean
enum: [false]
errorCode:
type: string
example: "00002"
errorMsg:
type: string
example: "duplicated account already exist"
In OpenAPI/Swagger 2.0, you can only use a single schema per response code, so the most you can do is define the varying fields as optional and document their usage in the model description
or operation description
.
swagger: "2.0"
...
definitions:
ApiResult:
type: object
properties:
result:
type: boolean
token:
type: string
errorCode:
type: string
errorMsg:
type: string
required:
- result