如何不在几乎所有路径中复制粘贴3个通用错误响应? [英] How not to copy-paste 3 generic error responses in almost all paths?

查看:81
本文介绍了如何不在几乎所有路径中复制粘贴3个通用错误响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望几乎所有路径都具有以下3种通用错误响应.我该如何在Swagger中描述而不将这些行复制粘贴到任何地方?

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'

推荐答案

好像我可以添加以下全局响应定义:

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'


与OpenAPI 3.0相同,不同之处在于它使用#/components/responses/...而不是#/responses/...:


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'


OpenAPI规范存储库中还有一个打开的功能请求,以添加对全局的支持/default操作响应.


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

这篇关于如何不在几乎所有路径中复制粘贴3个通用错误响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆