Play Union Types

API Builder provides support for declaring your own union types (sometimes referred to as sum or algebraic types). The basic idea is that you can express that a particular variable is one of a known set of types.

As an example, in an ecommerce system, you might want to accept orders from both registered users (people who actually have a username and password with your service) and also from guest users (e.g. people who have never visited your application before). One way to model this is to define two types, Registered User and Guest User, a single union type User that can be either a Registered User or a Guest User, and then to model your order as having a User.

Union types, especially when combined with expressive programming languages like Scala, can prove to be very useful and pragmatic tools for modeling problems like this.

Over the wire, union types in the play 2_x clients are represented in one of two ways based on the presence of the discriminator field.

With a discriminator

Union type is serialized as a Json Object with the discriminator field injected. For example, assume the discriminator field is 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"
    }
    

With no discriminator

Union type is serialized as a Json Object with one element. The key is the name of the type and the value is the Json serialization of the actual 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"
      }
    }
    

We also maintain example applications that demonstrate the use of the union types with and without discriminators. For more information: