Search code examples
swaggerswagger-uiswagger-2.0swagger-codegenswagger-editor

how to make parent model's variables as not required in child model, provided all the parent variables are marked as required?


I have a parent definition which is extended by a child definition using allOf keyword. Since i have marked all the variables as required in parent model , it is being marked as required in child ,model too. But i need the parent variable to be marked as not required. Any ideas?

definitions: 
  Parent:
    type: "object"
    required:
      - "id"
    properties:
      id:
        type: "integer"
        format: "int64"
        minimum: 1
        example: "123456"        

  Child:
    allOf:
      - $ref: "#/definitions/Parent"
    type: "object"
    required: 
      - "sample"
    properties:
      sample:
        type: "string"
        format: "full-date"
        example: "2001/12/31"

Solution

  • You cannot un-require a parent model's fields in child models. The workaround is to define a base model, say, ParentBase, with optional properties and inherit both Parent and Child from this model.

    definitions:
      ParentBase:
        type: object
        properties:
          id:
            type: integer
            format: int64
            minimum: 1
            example: 123456
    
      Parent:
        allOf:
          - $ref: "#/definitions/ParentBase"
          - required:
              - id
    
      Child:
        allOf:
          - $ref: "#/definitions/ParentBase"
          - type: object
            required: 
              - sample
            properties:
              sample:
                type: string
                format: full-date
                example: "2001/12/31"
    


    On an unrelated note, the id property is defined as an integer but its example value is a string. This is wrong - the example data type should match the property type. You need to use 123456 without quotes.

    id:
      type: integer
      #example: "123456"  # Wrong
      example: 123456     # Correct