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

JsonApiRest

Json Problem Overview


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"
}

Json Solutions


Solution 1 - Json

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.

Solution 2 - Json

There is no clear winner. And because there is not, clients should never technically depend on any convention about this, clients should not expect either shape.

  • removing null values to reduce bandwidth usage is commonly not justified (unless the number of null fields is large and the bandwidth noticeably suffers).
  • removing null values to allow human readers to more easily see actual values is not commonly justified, APIs are not man-machine interfaces
  • keeping null values to allow human readers to more easily see document structure is not commonly justified, APIs are not man-machine interfaces, and API responses are not API documentation
  • keeping null values to allow dirty clients to parse the json in specific ways is commonly not justified, clients should be written cleanly as tolerant readers
  • keeping null values only where the corresponding create method (POST/PUT) requires explicit passing of null would make sense, but is commonly difficult to achieve
  • keeping the output same as the request during creation could make sense when each document has its own owning client, but is commonly difficult to achieve
  • A special case to consider is partial responses triggered by something like ?fields=foo,bar where returning nulls for all other fields seems a bit counter-intuitive

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDennis LaumenView Question on Stackoverflow
Solution 1 - JsonPeteView Answer on Stackoverflow
Solution 2 - JsontkruseView Answer on Stackoverflow