API / Swagger Interview questions
How do you handle polymorphism and discriminators in OpenAPI schemas?
OpenAPI describes polymorphic schemas — where a field could hold one of several different possible object shapes — using the oneOf keyword combined with a discriminator, which tells consuming tools which specific field in the payload determines which of the possible schemas actually applies.
Pet: oneOf: - $ref: '#/components/schemas/Dog' - $ref: '#/components/schemas/Cat' discriminator: propertyName: petType mapping: dog: '#/components/schemas/Dog' cat: '#/components/schemas/Cat'
Without a discriminator, a tool receiving a payload matching a oneOf schema would need to attempt validation against every listed sub-schema to figure out which one actually matches, which is both slower and can be genuinely ambiguous if more than one sub-schema happens to validate successfully; the discriminator's propertyName tells the tool exactly which field to inspect first, and the optional mapping makes the correspondence between that field's value and the target schema completely explicit.
This pattern is common for anything with a shared base shape but type-specific fields — a payments API describing different payment method types, or a notifications API describing different channel types — where a single endpoint's response or request body can legitimately take one of several concrete forms.
More Related questions...