How not to copy-paste 3 generic error responses in almost all paths?

天大地大妈咪最大 提交于 2019-12-19 05:36:05

问题


I want almost all my paths to have the following 3 generic error responses. How do I describe that in Swagger without copypasting these lines everywhere?

    401:
      description: The requester is unauthorized.
      schema:
        $ref: '#/definitions/Error'
    500:
      description: "Something went wrong. It's server's fault."
      schema:
        $ref: '#/definitions/Error'
    503:
      description: Server is unavailable. Maybe there is maintenance?
      schema:
        $ref: '#/definitions/Error'

Example of how I use this in a request:

paths:
    /roles:
      get:
        summary: Roles
        description: |
          Returns all roles available for users.
        responses:
          200:
            description: An array with all roles.
            schema:
              type: array
              items:
                $ref: '#/definitions/Role'
          401:
            description: The requester is unauthorized.
            schema:
              $ref: '#/definitions/Error'
          500:
            description: "Something went wrong. It's server's fault."
            schema:
              $ref: '#/definitions/Error'
          503:
            description: Server is unavailable. Maybe there is maintenance?
            schema:
              $ref: '#/definitions/Error'

回答1:


Looks like I can add the following global response definition:

# An object to hold responses that can be used across operations.
# This property does not define global responses for all operations.
responses:
  NotAuthorized:
    description: The requester is unauthorized.
    schema:
      $ref: '#/definitions/Error'

However I will still need to reference it in paths like this:

401:
  $ref: '#/responses/NotAuthorized'


Same thing in OpenAPI 3.0, except it uses #/components/responses/... instead of #/responses/...:

openapi: 3.0.0

# An object to hold responses that can be used across operations.
# This property does not define global responses for all operations.
components:
  responses:
    NotAuthorized:
      description: The requester is unauthorized.
      schema:
        $ref: '#/components/schemas/Error'

# Then, in operation responses, use:
...
401:
  $ref: '#/components/responses/NotAuthorized'


There's also an open feature request in the OpenAPI Specification repository to add support for global/default responses for operations.




回答2:


It doesn't look like the Open API specification supports this.



来源:https://stackoverflow.com/questions/35921287/how-not-to-copy-paste-3-generic-error-responses-in-almost-all-paths

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!