Swagger YAML规范,有条件的必填字段

时间:2018-12-19 09:20:43

标签: swagger

我想为REST POST服务创建YAML架构。

 requestBody:
        description: Details of the request
          required: true
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CreateCompanyRequest'
components:
  schemas:
    CreateCompanyRequest:
      description: The requested data to the service.
      type: object
      required:
        - address
        - identifier
        - type

以及如何指定identifier字段为type字段值=“ BIG”时必须填写?

或者也许identifier字段不应该在必填列表中,相反,我应该在某处添加一些注释以使第三方了解api的要求?

1 个答案:

答案 0 :(得分:0)

OpenAPI 3.0 允许我们在代表超集的模型中将属性定义为 discriminator。然后,您可以创建代表子集的其他模型,这些模型可以更改模型属性所需的标志。 Swaggers 文档中的示例 https://swagger.io/docs/specification/data-models/oneof-anyof-allof-not/

Pet:
  type: object
  required:
    - pet_type
  properties:
    pet_type:
      type: string
  discriminator:
    propertyName: pet_type
Dog:     # "Dog" is a value for the pet_type property (the discriminator value)
  allOf: # Combines the main `Pet` schema with `Dog`-specific properties 
    - $ref: '#/components/schemas/Pet'
    - type: object
      # all other properties specific to a `Dog`
      required:
        - bark
      properties:
        bark:
          type: boolean
        breed:
          type: string
          enum: [Dingo, Husky, Retriever, Shepherd]
Cat:     # "Cat" is a value for the pet_type property (the discriminator value)
  allOf: # Combines the main `Pet` schema with `Cat`-specific properties 
    - $ref: '#/components/schemas/Pet'
    - type: object
      # all other properties specific to a `Cat`
      properties:
        hunts:
          type: boolean
        age:
          type: integer