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" }
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With