Representing null values in a REST API

REST is been defacto standard for serving data to external consumers. While developing such REST APIs, I have come across an interesting basic and quite common case – what to do with attributes with null values in a json response. This a very basic but a very important question and there is lot of discussion around same with so many opinions. Here is an aggregated analysis and how you can take care of this scenario in your context.

For any data entity some attributes are required and some are optional. So question is what if there is no value for optional field. How do we represent that in our response.

Most important rule : “”(blank) or any character != null != “null”

This is common thing people tend to do with APIs. This basic data violation. Representing null values as any kind of string in json response is not right. At least its not intuitive for a consumer. This option is an absolute “NO”. We have following two options

{
	"requiredField":"Some value must be here",
	"someOptionalField":null	
}

{
	"requiredField":"Some value must be here",
}

Is there any semantic difference between null and undefined in your context.

In javascript having an attribute in json with null and not having one (undefined) are completely different. Read more here. Consider following clauses for above data.

Attribute with null Attribute absent
data.someOptionalField == null true true
data.someOptionalField === null true false
data.someOptionalField === undefined false true

If your consumer has different processing for null and undefined, then you must go with attribute present with null value in data (1st format), otherwise I would suggest second format because of simple reason – Smaller payload. This would be big gain especially when there are many optional fields.

There were some arguments about readability. There are two solutions to this. One ask the consumer to refer to REST API documentation which can be easily created with so many tools these days. Other is something I have seen with mygov.in data APIs (by Indian govt), response contains information entity like all attributes and their type, required information. Second approach with a flag which omits that information would also be nice.

Basically decision depends on you context. If you have more suggestion please share with community.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s