如何在Swagger中为所有路径添加401响应

Ext*_*ion 4 response swagger

我有一个休息api,我想在Swagger中记录.在所有请求中,API都可以使用401响应.

因此,不是为每条路径一次又一次地再次定义401(不是那么干).我想定义所有路径都可以返回401.

这可能吗?

小智 11

我不认为这是一个完美的解决方案,但我这样做是为了试图干掉它.

在根据swagger模式中,您可以定义一个responses对象,该对象由Swagger规范定义:

用于保存可跨操作使用的响应的对象.此属性未定义所有操作的全局响应.

responses:
  400:
    description: Bad Request
    schema:
      $ref: '#/definitions/Error'
  401:
    description: Unauthorized
    schema:
      $ref: '#/definitions/Error'
  403:
    description: Forbidden
    schema:
      $ref: '#/definitions/Error'
  500:
    description: Internal Server Error
    schema:
      $ref: '#/definitions/Error'

definitions:
  Error:
    type: object
    required:
      - message
    properties:
      message:
        type: string
        description: 'The cause of the Error.'
Run Code Online (Sandbox Code Playgroud)

完成后,您可以在路径中引用共享响应.

paths:
  /keys/:
    get:
      summary: 'Get All API Keys the caller has access to view.'
      responses:
        200:
          description: 'Successfully got Keys'
          schema:
            $ref: '#/definitions/ApiKeyResponse'
        400: 
          $ref: '#/responses/400'
        401:
          $ref: '#/responses/401'
        500:
          $ref: '#/responses/500'
Run Code Online (Sandbox Code Playgroud)

这至少可以使您了解response描述以及为该响应类型定义的任何模式.我真的希望有一种方法可以将所有常见的错误响应分组,只是引用该组,但我还没有找到任何方法来做到这一点.


Sam*_*ada 2

据我所知,这是不可能的。您需要使用 @ApiResponse 注释每个 API 端点。类级别唯一可用的注释是 @Api 和 @ApiModel 。欲知详情,请参阅此链接 -

http://docs.swagger.io/swagger-core/v1.5.0/apidocs/io/swagger/annotations/ApiModel.html