enumsswaggeropenapi

OpenAPI subset of a property with a $ref


I'm building out a schema A which has a property that references another schema B. The problem I'm having is I only need a subset of a enum property in schema B. Is there a way to do this within the yaml file? Simplified Example, If I was building something for a Veterinarian Office:

components:
  schemas:
    Dog:
      properties:
        color:
          description: Color of the dog
          $ref: "#/comonents/schema/color"
        injury:
          description: Information about the injury
          $ref: "#/comonents/schema/InjuryInfo"
    
    InjuryInfo:
      properties:
        location:
          description: where on the animal is the injury
          type: string
          enum: 
            - Body
            - Leg
            - Wing
        details:
          description: Additional Details
          type: string
        otherProperty:
          description: Some other property
          type: string

What I need to do is reuse the InjuryInfo schema but I need the Dog schema to only allow for properties InjuryInfo.location and InjuryInfo.details. And for the Dog.injury.location to only include a subset of the enum values. Is this possible from the yaml file?


Solution

  • You can use allOf for these purposes. Here you can read more about allOf

    components:
      schemas:
        Dog:
          type: object
          properties:
            color:
              description: Color of the dog
              $ref: "#/components/schemas/Color"
            injury:
              allOf:
                - $ref: "#/components/schemas/InjuryInfo"
                - type: object
                  properties:
                    location:
                      enum:
                        - Body
                        - Leg
                  required:
                    - location
                    - details
    
        InjuryInfo:
          type: object
          properties:
            location:
              type: string
              enum:
                - Body
                - Leg
                - Wing
            details:
              type: string
            otherProperty:
              type: string