62

Say in my application, some users give us their last name, and others do not. In a REST API response, which body is preferred:

With a "null" value:

{"firstName": "Bob",
 "lastName": null}

Or just a missing key:

{"firstName": "Bob"}
jtmarmon
  • 958
  • 1
  • 8
  • 12

1 Answers1

47

Consider removing empty or null values.

If a property is optional or has an empty or null value, consider dropping the property from the JSON, unless there's a strong semantic reason for its existence.

{
  "volume": 10,

  // Even though the "balance" property's value is zero, it should be left in,
  // since "0" signifies "even balance" (the value could be "-1" for left
  // balance and "+1" for right balance.
  "balance": 0,

  // The "currentlyPlaying" property can be left out since it is null.
  // "currentlyPlaying": null
}

Further Reading
Google Style Guide - Empty or Null Property Values
Should null values be included in JSON responses from a REST API?

Robert Harvey
  • 198,589
  • 55
  • 464
  • 673
  • thanks for the link, Robert. so even if `currentlyPlaying` will be in some responses and not other, it's preferrable to have the client check if the key is there or not rather than check if it's null? – jtmarmon May 26 '15 at 20:00
  • `null` and `undefined` have *almost* the same meaning in Javascript, and [you can check for both](http://programmers.stackexchange.com/a/268125/1204) using `if (myProperty == null)` – Robert Harvey May 26 '15 at 20:01
  • well actually in my case the client might be java, objective-c, or javascript. the link within the second link (API-craft) indicates to me that null fits our semantic use case, but mostly that I should just make a decision and stick to it :P thanks again – jtmarmon May 26 '15 at 20:10
  • Simple: If the application needs to distinguish between different values, then the server must provide different values, otherwise it need not and should not. Does your app need to distinguish between a key not being present, a key have an empty string as a value, and a key having a null value? – gnasher729 May 27 '15 at 10:50
  • 9
    The [answer in this post](http://stackoverflow.com/questions/21188145/is-it-worth-to-exclude-null-fields-from-a-json-server-response-in-a-web-applicat) addresses some good reasons as to why you should not remove null fields. – Dave New Nov 16 '15 at 14:57