When designing APIs with OpenAPI, oneOf often looks intimidating. It’s powerful, but easy to misuse especially with PATCH endpoints. Let’s break it down simply.
What is oneOf?
In OpenAPI (JSON Schema), oneOf means:
The request body must match exactly one schema from the list.
Not zero.
Not two.
Exactly one.
Example:
schema:
oneOf:
- $ref: '#/components/schemas/InverterPatch'
- $ref: '#/components/schemas/EVPatch'
- $ref: '#/components/schemas/EVCSPatch'
This tells OpenAPI:
“The payload must conform to exactly one of these schemas.”
Why oneOf is tricky with PATCH
PATCH requests are partial updates. Clients often send only a few fields.
Now imagine this payload:
{
"reverseFlow": true
}
If reverseFlow exists in:
InverterPatchEVCSPatch
Then this payload matches more than one schema.
🚫 Result: Validation fails, because oneOf requires exactly one match.
Enter the Discriminator
A discriminator solves this ambiguity.
discriminator:
propertyName: type
Now the client sends:
{
"type": "inverter",
"reverseFlow": true
}
OpenAPI immediately knows:
type = inverter- → use
InverterPatch - → validation succeeds
💡 The discriminator tells OpenAPI which schema to validate against.
When You SHOULD Use oneOf
Use oneOf (with a discriminator) when:
- You have multiple schemas
- Some fields overlap
- Clients may send partial updates
- You want OpenAPI-level validation, not just backend logic
When You Should NOT Use oneOf
Avoid oneOf if:
- You don’t need OpenAPI to pick between schemas
- Backend already knows the resource type
- You’re okay validating type-specific rules at runtime
In those cases, a single PATCH schema with optional fields is simpler and often better.
Key Takeaway
-
oneOf= exactly one schema must match - Overlapping fields + PATCH = ambiguity
- Discriminator resolves ambiguity
- Don’t use
oneOfunless you actually need schema selection
Used correctly, oneOf makes your API safer and self-documenting. Used incorrectly, it makes PATCH endpoints painful.
Top comments (0)