Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should null values be included in JSON responses from a REST API? [closed]

Tags:

json

rest

api

I'm in the process of designing and developing a RESTful API. I'm taking a pragmatic, resource oriented approach to the API (resource oriented, uniform interface, addressability, but no real HATEOAS). One point I'm not sure about though is how to approach null values in objects.

Should I include fields with null values in the APIs responses?

Example:

{     "fieldA": "AAA",     "fieldB": null } 

Or, should I just leave out these fields altogether if the system has no data for these fields?

Example:

{     "fieldA": "AAA" } 
like image 470
Dennis Laumen Avatar asked Mar 28 '13 16:03

Dennis Laumen


People also ask

Should JSON include null values?

You should definitely include it if there is any need to distinguish between null and undefined since those have two different meanings in Javascript. You can think of null as meaning the property is unknown or meaningless, and undefined as meaning the property doesn't exist.

Should API return null or empty string?

If you usually return an array, and empty array is probably a good choice. But if you usually return an object, then, IMHO, null is acceptable and may be better than an empty object. If you usually return just a string or a number, then null would probably be the preferred choice.

What happens if you send a null value in an API call?

If a "NULL" is passed in the JSON, we get NULL in the object, but any other field that is not passed is NULL as well. Therefore we cannot distinguish which field can be deleted and which field cannot be touched. The complete object is sent.


1 Answers

There was a discussion about this recently on API-Craft. The general consensus was there is potentially a semantic difference between the omission of a value, versus an inclusion of a null value.

If there is no semantic value to be gained for your specific use case, then I would say look at your target consumers of the API, and think about whether omitting the value will cause them problems.

like image 147
Pete Avatar answered Oct 02 '22 21:10

Pete