Discriminator Mapping vs. Strict oneOf for Polymorphic Validation
0 reputation · 28 Apr 2024, 07:48 UTC
Polymorphic Payload Modeling in OpenAPI 3.1
When defining request bodies that can accept multiple object types, developers typically choose between using a discriminator object for explicit mapping or relying on oneOf for structural validation. This decision impacts how tooling handles type dispatch and how validators react to ambiguous payloads.
Tooling and Validation Constraints
The discriminator object facilitates automatic class hierarchy generation in tools like OpenAPI Generator. However, because the discriminator is not a native JSON Schema validation keyword, some validators ignore it and fall back to the underlying oneOf or anyOf logic. This creates a discrepancy where a payload might be logically invalid according to the discriminator mapping but structurally valid according to the schema.
Conversely, using oneOf without a discriminator requires the validator to check every possible schema. In scenarios where sub-schemas overlap, this can lead to ambiguous matches or performance degradation during validation.
- Discriminator approach: Optimizes for code generation and documentation but may fail silently if the discriminator field is missing or unknown.
- Strict oneOf approach: Ensures structural integrity and loud validation failures but increases complexity for client-side type casting.
Given these differing failure modes, what is the recommended strategy for ensuring that a discriminator field is strictly enforced as required during runtime validation across diverse toolchains? Should the discriminator be mirrored as a required property within each sub-schema to bridge the gap between metadata and validation?