如何对ID参数和ID架构属性使用相同的定义?

时间:2018-12-18 07:47:04

标签: openapi

我想知道OpenAPI中是否有一种方法可以描述用作路径参数的user_idid对象的User字段是同一类型的值。这样的好处是重用了描述和示例。

openapi: 3.0.1
info:
  title: Test API
  version: 1.0.0
paths:
  /foo/{user_id}:
    get:
      parameters: 
        - $ref: '#/components/parameters/user_id'
      responses:
        '200':
          description: A user
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
components:
  parameters:
    user_id:
      name: user_id
      in: path
      required: true
      description: the id of a User, from parameters
      example: ghijkl
      schema:
        type: string
  schemas:
    User:
      type: object
      properties:
        id: 
          type: string
          description: the id of a User, from schemas
          example: abcdef

我不想重新定义用户ID的示例和说明。

1 个答案:

答案 0 :(得分:1)

您可以为用户ID定义单独的架构,并让参数/属性schema引用用户ID架构:

components:
  parameters:
    user_id:
      name: user_id
      in: path
      required: true
      schema:
        $ref: '#/components/schemas/UserId'   # <-------
  schemas:
    UserId:
      type: string
      description: The ID of a User
      example: abcdef
    User:
      type: object
      properties:
        id: 
          $ref: '#/components/schemas/UserId' # <-------

Swagger编辑器和Swagger UI将从架构示例中获取参数示例,但是当前未从架构描述中获取参数描述。随时提交enhancement request