Search code examples
jsonapi-design

JSON: "type" field or dynamic fields?


What is the best practice on serializing mutually exclusive data that has the same type (programming-wise) but different "meaning" and different logic supposed to handle it?

As an example, let's say we want to design an API that handles account recovery. It can be done by either e-mail or SMS (which is different logic on the backend).

So if we want to compose a request to this API, we can approach it dynamically, i.e. client sends:

{"email":"my@email.com"}

or

{"phone":"+123456789"}

Alternatively, we set up a "typesafe" json, i.e.:

{"type":"email", "value":"my@email.com"}

or

{"type":"phone", "value":"+123456789"}

Which of these two approaches is considered better practice?


Solution

  • It all depends on your use-case, but I can make a few recommendations:

    1. Take a look at Typescript. It might help you for some of these cases.
    2. Strictly on API validation, JSON-Schema is great. You can easily express both of your examples and strictly validate.

    Personally I would not use a separate "type" field, because the type is already implied from the existence of the email/phone property and it's easier to deal with properties that are always the same type.

    However, if I were to design an API where either an email or a phone could appear in a field, I would probably use URI's for this instead:

    mailto:foo@example.org
    tel:+15551234567