How to vary response body type based on different failures in OpenAPI?

Given an openapi documented endpoint that returns a standard data type:

responses:
  '200':
    $ref: '#/components/schemas/DataType'

How can varying failure causes be documented in OpenApi spec?

For example, there may be an error due to a bad client foo parameter, in which case I want to return a 400 with body

{"bad_foo_parameter" : "the underlying foo problem"}

While there could be a different bad bar response:

{"bad_bar_parameter": "the underlying bar problem"}

How can I use openapi to document the two different response object types?

There is a similar question that asks about varying based on parameters, I am asking for variance based on error type.

Thank you in advance for your consideration and response.

Upvotes: 0

Views: 460

Answers (2)

Jeremy Fiel
Jeremy Fiel

Reputation: 3307

This is why RFC9457 exists. The problem+json model is a generic error schema to relay this type of information back to the client. Your code should implement this generic schema for all of your errors so it returns a consistent response.

In OAS, you can document multiple examples of this response.

responses:
  "400":
    content:
      "application/problem+json":
        schema:
          $ref: "#/components/schemas/problem+json" // define the schema in the components section per the RFC. 
        examples:
          bad_param_1:
            value: {...}
          bad_param_2:
            value: {...}

Upvotes: 1

As of version 3.0 there is a oneOf descriptor for multiple types:

responses:
  '400':
    description: Bad Request
    content:
      application/json:
        schema:
          oneOf:
            - $ref: '#/components/schemas/BadFooError'
            - $ref: '#/components/schemas/BadBarError'

Upvotes: 0

Related Questions