Speakeasy Logo
Skip to Content

oneOf, allOf, anyOf: composition and inheritance in OpenAPI

OpenAPI allows us to combine object schemas using the keywords allOf, anyOf, and oneOf.

These keywords correspond to the following logical operators:

Keyword
Operator
Description
An exclusive disjunction. Instances must satisfy exactly one of A, B, or C.
How to use
Use for describing Union Types
Operator
Description
A union of all subschemas. Instances must satisfy all of A, B, and C.
How to use
Use for describing model composition: the creation of complex schemas via the composition of simpler schemas.
Operator
Description
An inclusive disjunction. Instances must satisfy at least one of A, B, or C.
How to use
There is no established convention about how anyOf should be interpreted. Use with extreme caution

The example below illustrates the different composition keywords:

Discriminator Object in OpenAPI

When using oneOf to indicate that a request body or response contains exactly one of multiple Schema Objects, a discriminator object can help the client or server figure out which schema is included in the request or response.

The discriminator object in OpenAPI tells a client or server which field can be used to discriminate between different schemas.

Field
Type
String
Required
Description
The property name used to discriminate between schemas.
Type
Map[string, string]
Required
Description
An optional map of values and schema reference strings.
Required
Description
Any number of extension fields can be added to the discriminator object that can be used by tooling and vendors.

In the example below, the Speakeasy Bar can receive one of two order types: A drink order with a bar-counter reference or an ingredient order with a delivery address:

If we include a discriminator object, the client can indicate the order type so that the server does not need to figure that out:

In the previous example, the value of the orderType property will determine the order type. The value of orderType must match one of the schema components, so must be either DrinkOrder or IngredientOrder.

To use values that don’t match a schema key, a discriminator object can include a mapping property that maps values to schemas. Here’s an example:

Last updated on