When a payload can be one of several different schemas (using oneOf, anyOf, or allOf), use a discriminator object to aid in serialization, deserialization, and validation. The discriminator identifies which property in the payload determines the specific schema to use.
Requirements:
- The
discriminator field MUST be a required field. - The
propertyName within the discriminator object is REQUIRED. - Inline schema definitions (schemas without an ID) cannot be used in polymorphism.
- The
discriminator object is only legal when using oneOf, anyOf, or allOf.
Example of Polymorphic Pets:
Pet:
type: object
discriminator:
propertyName: petType
properties:
name:
type: string
petType:
type: string
required:
- name
- petType
Cat:
allOf:
- $ref: '#/components/schemas/Pet'
- type: object
properties:
huntingSkill:
type: string
enum:
- clueless
- lazy
- adventurous
- aggressive
required:
- huntingSkill
components:
schemas:
Pet:
type: object
discriminator:
propertyName: petType
properties:
name:
type: string
petType:
type: string
required:
- name
- petType
Cat:
description: A representation of a cat
allOf:
- $ref: '#/components/schemas/Pet'
- type: object
properties:
huntingSkill:
type: string
description: The measured skill for hunting
enum:
- clueless
- lazy
- adventurous
- aggressive
required:
- huntingSkill
Dog:
description: A representation of a dog
allOf:
- $ref: '#/components/schemas/Pet'
- type: object
properties:
packSize:
type: integer
format: int32
description: the size of the pack the dog is from
default: 0
minimum: 0
required:
- packSize