如何重构此Swagger API规范

时间:2015-11-13 14:48:43

标签: swagger swagger-ui swagger-2.0 swagger-editor

我有几个端点,我有一些标准的错误响应,如404401403default。我想将这些响应重构为Swagger定义,但我无法实现这一点。我尝试了一些技巧,但它总是导致解析错误。这是我的yaml。

swagger: '2.0'
info:
  title: My API
  description: My API description
  version: 0.0.1
host: api.example.com
schemes:
  - https
basePath: /
produces:
  - application/json
paths:
  /users:
    get:
      operationId: getUsers
      summary: Get users
      description: Get all users
      tags:
        - Users
      responses:
        '200':
          description: An array of users
          schema:
            type: array
            items:
              $ref: '#/definitions/User'
        '401':
          description: Authentication required
          schema:
            $ref: '#/definitions/Error'
        '402':
          description: Payment required
          schema:
            $ref: '#/definitions/Error'
        '403':
          description: Unauthorized access
          schema:
            $ref: '#/definitions/Error'
        '404':
          description: Not found
          schema:
            $ref: '#/definitions/Error'
        default:
          description: Unexpected error
          schema:
            $ref: '#/definitions/Error'
  /games:
    get:
      operationId: getGames
      summary: Get games
      description: Get all games
      tags:
        - Games
      responses:
        '200':
          description: An array of games
          schema:
            type: array
            items:
              $ref: '#/definitions/Game'
        '401':
          description: Authentication required
          schema:
            $ref: '#/definitions/Error'
        '402':
          description: Payment required
          schema:
            $ref: '#/definitions/Error'
        '403':
          description: Unauthorized access
          schema:
            $ref: '#/definitions/Error'
        '404':
          description: Not found
          schema:
            $ref: '#/definitions/Error'
        default:
          description: Unexpected error
          schema:
            $ref: '#/definitions/Error'
definitions:
  User:
    type: object
    properties:
      id:
        type: integer
        description: Unique id of user
      name:
        type: string
        description: Name of user
  Game:
    type: object
    properties:
      id:
        type: integer
        description: Unique id of game
      name:
        type: string
        description: Name of game
  Error:
    type: object
    properties:
      code:
        type: integer
        description: HTTP status code
      message:
        type: string
        description: Message describing error

观察/users/games中的重复回复。如何重构并将其移至definitions

1 个答案:

答案 0 :(得分:1)

您可以使用共享responses对象来定义响应。然后在各个操作中引用它们。从spec关于共享响应对象:

  

保持响应以在操作中重用的对象。响应   定义可以参考这里定义的定义。

虽然这是一个有效的规范,但Swagger-UI无法从除default响应之外的共享响应中解析。以下是与此相关的issue