API / Swagger Interview questions
When should you use the allOf, oneOf, and anyOf keywords in OpenAPI schemas?
These three keywords all combine multiple schemas, but they express different logical relationships between them, and picking the wrong one produces validation behavior that doesn't match the intended data shape.
| Keyword | Meaning | Typical Use |
| allOf | Data must satisfy every listed schema | Composing/extending a base schema with additional fields |
| oneOf | Data must satisfy exactly one listed schema | True polymorphism, e.g. Dog vs Cat |
| anyOf | Data must satisfy at least one listed schema | A value that could match overlapping shapes, not mutually exclusive |
allOf is the one most often used for schema reuse — combining a shared BaseEntity schema (with common fields like id and createdAt) with entity-specific fields, similar in spirit to inheritance; oneOf is the right choice specifically when the possible shapes are mutually exclusive alternatives, which is also the scenario where pairing it with a discriminator becomes valuable.
A common mistake is reaching for oneOf when anyOf is actually correct, or vice versa: if a value could legitimately match more than one of the listed schemas at once without that being a data error, oneOf's strict "exactly one" semantics will incorrectly reject otherwise-valid data.
More Related questions...