Play Union Types
Model type-safe alternatives with union types. Express that a variable is exactly one of a known set of types — the generated Play clients handle serialization and deserialization automatically.
For example, in an ecommerce system you might accept orders from both registered users (with
a username and password) and guest users (first-time visitors). Define a registered_user type and a guest_user type, then combine them into a single user union type and reference it from your order model.
Over the wire, union types in the Play 2.x clients are represented in one of two ways based on the presence of a discriminator field.
D With a discriminator
The union type is serialized as a JSON object with the discriminator field injected.
For example, with the discriminator set to "type":
Example serializations:
{
"type": "registered_user",
"guid": "f30dc64e-1793-4d59-aa47-71f000e06851",
"email": "registered@test.apibuilder.io"
} {
"type": "guest_user",
"guid": "f30dc64e-1793-4d59-aa47-71f000e06851",
"email": "guest@test.apibuilder.io"
}W Without a discriminator
The union type is serialized as a JSON object with one element — the key is the type name and the value is the serialized object.
Example serializations:
{
"registered_user": {
"guid": "f30dc64e-1793-4d59-aa47-71f000e06851",
"email": "registered@test.apibuilder.io"
}
} {
"guest_user": {
"guid": "f30dc64e-1793-4d59-aa47-71f000e06851",
"email": "guest@test.apibuilder.io"
}
}⚙ Example Applications
Working examples demonstrating union types with and without discriminators:
Ready to define your own union types?
View api.json Specification