OpenAPI discriminators are a feature of the OpenAPI Specification (formerly known as Swagger) that allows you to define alternative schemas for different values of a property.
In other words, you can use a discriminator to specify different schema definitions based on the value of a property. For example, you may have an "animal" schema with a discriminator property called "type". The "type" property could have possible values of "cat" or "dog". You could then define different schema definitions for the "cat" and "dog" types.
Discriminators are especially useful for modeling inheritance in your API schema. By using discriminators, you can define common properties and behaviors for a group of related schemas, while still allowing for differences in their specific implementations.
The discriminator property is used to select the appropriate schema definition for a given value. The value of the discriminator property is typically found in the JSON payload of a request or response.
Let's say we want to define a schema for different types of animals, with common properties like "name" and "age", but with different properties based on the type of animal. We can use a discriminator to define alternative schemas based on the value of the "type" property:
components:
schemas:
Animal:
type: object
properties:
name:
type: string
age:
type: integer
discriminator:
propertyName: type
required:
- type
Dog:
allOf:
- $ref: '#/components/schemas/Animal'
- type: object
properties:
breed:
type: string
Cat:
allOf:
- $ref: '#/components/schemas/Animal'
- type: object
properties:
color:
type: string
In this example, we define a base schema called "Animal" with properties for "name" and "age", and a discriminator called "type" that will be used to select the appropriate schema for each animal. We also define two alternative schemas called "Dog" and "Cat", which extend the "Animal" schema with additional properties specific to dogs and cats.
If a request or response payload includes an animal with a "type" property of "dog", the schema definition for "Dog" will be used. Similarly, if the "type" property is "cat", the "Cat" schema will be used.
Here's an example payload for a dog:
{
"type": "dog",
"name": "Fido",
"age": 3,
"breed": "Golden Retriever"
}
And here's an example payload for a cat:
{
"type": "cat",
"name": "Whiskers",
"age": 2,
"color": "tabby"
}
In this way, discriminators allow you to define flexible, extensible API schemas that can adapt to a variety of use cases.