How to set the Accept header globally in OpenAPI 3

2020-04-07 03:05发布

问题:

I have a new OpenAPI setup via SwaggerHub. Is there an option to force a certain Accept header globally?

I have set up the Content-Type on the response:

openapi: 3.0.0

paths:
  /test-path:
     get:
       responses:
         '200':
           description: OK
           content:
             application/vnd.company.v1.0.0+json:

When inserting a different Accept header via cURL request, the following out is made:

{"message":"Missing matching response for specified Accept header"}

That makes sense, since we aren't providing any response for that.

回答1:

Unlike OpenAPI/Swagger 2.0, which has global consumes and produces, OpenAPI 3.0 requires that request and response media types be defined in each operation individually. There's no way to define the Content-Type or requests or responses globally.

You can, however, $ref common response definitions (such as error responses), which can reduce the repetition.

openapi: 3.0.2
...

paths:
  /foo:
    get:
      responses:
        '400':
          $ref: '#/components/responses/ErrorResponse'
  /bar:
    get:
      responses:
        '400':
          $ref: '#/components/responses/ErrorResponse'


components:
  responses:
    ErrorResponse:
      description: An error occurred
      content:
        application/vnd.error+json:
          schema:
            ...