Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 37 ยท Paths, Schemas and Components

OpenAPI allOf, oneOf, anyOf, not and Discriminator Explained

Combine schemas in OpenAPI: allOf for inheritance, oneOf and anyOf for alternatives, not, discriminator for polymorphism, with a live evaluator and design pitfalls.

Real data is not always one flat shape. A payment may be a card or a bank transfer. A Dog is a Pet plus a few extra fields. OpenAPI (through JSON Schema) offers four composition keywords to express this: allOf, oneOf, anyOf and not. Combined with the OpenAPI-specific discriminator, they describe inheritance and polymorphism.

The four keywords at a glance

Keyword A value is valid when it matches... Think of it as
allOf all listed schemas AND, "extends"
oneOf exactly one listed schema XOR, "is one of these kinds"
anyOf at least one listed schema OR
not the schema does not match NOT
flowchart TD
  V["Incoming value"] --> A["allOf: must pass A and B"]
  V --> O["oneOf: pass exactly one of A, B"]
  V --> Y["anyOf: pass one or more of A, B"]
  V --> N["not: must fail A"]

The keywords answer different questions about the same value.

allOf: reuse and extend

allOf is how you express "a Dog is a Pet with extra properties":

YAML
components:
  schemas:
    Pet:
      type: object
      required: [name]
      properties:
        name: { type: string }
    Dog:
      allOf:
        - $ref: "#/components/schemas/Pet"
        - type: object
          required: [breed]
          properties:
            breed: { type: string }
            barks: { type: boolean }

A Dog must satisfy Pet (it needs a name) and the second schema (it needs a breed). Many code generators turn this into a subclass.

additionalProperties: false inside one allOf branch rejects the properties of its siblings, so inherited objects can never validate. Use unevaluatedProperties: false on the outer schema in OpenAPI 3.1 instead.

oneOf: alternatives

YAML
Payment:
  oneOf:
    - $ref: "#/components/schemas/CardPayment"
    - $ref: "#/components/schemas/BankTransfer"

The value must match exactly one branch. If a value matches two, it is invalid, so make the branches mutually exclusive (for example with a required, constant type field).

anyOf: flexible alternatives

anyOf accepts a value that matches one or more branches. It suits "this or that or both" cases such as a search filter that may contain a name, an email, or both:

YAML
Contact:
  anyOf:
    - required: [email]
    - required: [phone]

This says "at least one of email or phone must be present."

not

YAML
NotAdmin:
  type: string
  not:
    enum: [root, admin]

Rarely used, but handy for banning a few values.

discriminator: tell the tool which branch to pick

With oneOf, a client reading JSON has to guess the type. A discriminator names a property whose value identifies the branch:

YAML
Pet:
  oneOf:
    - $ref: "#/components/schemas/Cat"
    - $ref: "#/components/schemas/Dog"
  discriminator:
    propertyName: petType
    mapping:
      cat: "#/components/schemas/Cat"
      dog: "#/components/schemas/Dog"
Cat:
  type: object
  required: [petType, name]
  properties:
    petType: { const: cat }
    name: { type: string }
Dog:
  type: object
  required: [petType, name]
  properties:
    petType: { const: dog }
    name: { type: string }
    breed: { type: string }

Now {"petType": "dog", ...} is validated against Dog only, and generated code can pick the right class. Without a mapping, the value must equal the schema name (Cat, Dog).

The discriminator property must be required in every branch.

Evaluating compositions

This stand-in evaluates allOf, oneOf and anyOf over small object schemas and shows how a discriminator picks a branch, so you can see why "exactly one" matters.

Python Stand-in: evaluate allOf, oneOf, anyOf and discriminator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Design advice

  • Prefer allOf with one level of inheritance. Deep hierarchies produce confusing generated code.
  • If branches overlap, oneOf fails for valid data. Add a distinguishing required const property, or use anyOf.
  • Always add a discriminator to a oneOf that clients will deserialize.
  • Think twice about polymorphism in an API: a simple object with a type field and optional fields is often easier for consumers.
  • Test your compositions with real validators (see tooling) because code generators differ in how well they support them.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which keyword means "must match exactly one of the listed schemas"?

    oneOf requires exactly one match; overlapping branches therefore make valid data fail.
  2. 2. How do you express that Dog is a Pet with extra fields?

    allOf combines schemas, which most generators render as inheritance.
  3. 3. What does a discriminator name?

    propertyName points at the property that tells tools which schema to use.
  4. 4. Which keyword fits "at least one of email or phone"?

    anyOf accepts one or more matching branches.
  5. 5. Why is additionalProperties: false risky inside one allOf branch?

    Each branch is checked on its own, so extra properties from other branches fail. Use unevaluatedProperties on the outer schema.

Summary

  • allOf = AND (extension), oneOf = exactly one, anyOf = at least one, not = must not match.
  • discriminator.propertyName lets tools choose the right branch of a oneOf.
  • Keep branches mutually exclusive and the discriminator property required.
  • Use unevaluatedProperties (3.1) rather than additionalProperties: false with allOf.
  • Check how your code generator treats compositions before you rely on them.

Next: Security schemes overview