2026-09-28 · 8 min read
- openapi
- schema
- api
OpenAPI supports polymorphic payloads through JSON Schema composition keywords such as oneOf and anyOf. A discriminator object adds a property-name hint and optional mapping that documentation and code-generation tools can use to select a model.
The discriminator should improve tool behavior, not carry validation correctness by itself. Each payload must still satisfy the composition semantics implemented by the server validator.
Choose oneOf or anyOf deliberately
Use oneOf when exactly one variant must validate and anyOf when overlapping valid interpretations are acceptable. Many domain unions need oneOf plus unique literal tag constraints so their exclusivity is obvious and testable.
- Give each branch a stable business meaning.
- Require fields that distinguish the branch.
- Reject ambiguous overlap in a oneOf union.
- Avoid inheritance metaphors that hide wire behavior.
Make the tag part of every schema
Choose a discriminator property such as type, require it in each relevant branch, and constrain it to that branch's exact value with const where the supported OpenAPI dialect allows it or a single-value enum where required.
Define casing, Unicode, and unknown-value behavior. A propertyName declaration alone does not require the property or constrain its values, so omitting branch constraints creates divergent validation and generation behavior.
Use explicit stable mappings
Map serialized tag values to canonical schema references instead of relying on component names as implicit values. Component refactoring should not silently change the public payload vocabulary.
Confirm the target OpenAPI version and tooling support for mapping references, inline schemas, nested unions, and inherited properties. Keep mappings local enough that readers can audit every public variant.
Evolve the union compatibly
Adding a variant can break exhaustive generated clients even when tolerant servers accept it. Define how clients handle unknown tags, communicate version support, and stage generator updates before producers emit a new value.
Renaming a schema component should leave explicit wire values stable. Renaming a tag value is a protocol change that may require dual-reading, controlled migration, and a clear retirement window.
Verify validators and generators independently
Use Flashman's YAML/JSON converter for specifications, JSON formatter for payload fixtures, diff for generated artifacts, case converter for naming checks, and Markdown editor for the compatibility matrix.
Test every variant, missing and null tags, unknown and case-changed values, branch overlap, extra properties, inline and referenced branches, renamed components, nested unions, read/write models, documentation, validators, SDKs, and staged variant additions.