Ivan Skalauh
Ivan Skalauh

Reputation: 319

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":"[email protected]"}

or

{"phone":"+123456789"}

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

{"type":"email", "value":"[email protected]"}

or

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

Which of these two approaches is considered better practice?

Upvotes: 0

Views: 276

Answers (1)

Evert
Evert

Reputation: 99571

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:[email protected]
tel:+15551234567

Upvotes: 1

Related Questions