How can I add a 401 response to all paths in Swagg

2019-05-07 12:08发布

I have a rest api that I want to document in Swagger. On all requests the API can respond with a 401.

So instead of defining the 401 again again and again for each path (not so DRY). I want to define that all paths can return a 401.

Is this possible?

2条回答
唯我独甜
2楼-- · 2019-05-07 12:39

As far as i know, this is not possible. You will need to annotate each API endpoint with @ApiResponse. The only annotations available at the class level are @Api and @ApiModel . For details, please refer to this link -

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

查看更多
等我变得足够好
3楼-- · 2019-05-07 12:41

I don't think this is a perfect solution but I've done this in an attempt to DRY it up a bit.

In the root swagger schema you can define a responses object which, as defined by the Swagger Spec:

An object to hold responses that can be used across operations. This property does not define global responses for all operations.

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.'

Once you've done that you can reference the shared responses in the path.

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'

At a minimum this gets you consistency with regards to the response description and any schema defined for that response type. I was really hoping for a way to group all of the common error responses and just reference the group but I haven't found any way to do that.

查看更多
登录 后发表回答