Card 04/ 10

ConceptDifficulty: Intermediate2 min

Absent, Null and Empty: Three Different Answers

A missing field, a null and an empty string can mean "unchanged", "cleared" and "set to nothing".

A field can be absent from a JSON body, present with the value null, or present with an empty value such as "" or [], and the three can mean different things. In a PATCH using JSON Merge Patch, absent means leave the field unchanged, null means remove it, and "" means set it to an empty string. The contract must say, for each field, which of the three it allows and what each means.

Take a customer with a nickname, "Bea", and three PATCH requests that each mention the nickname differently.

Three merge-patch bodies for the same field, and the customer afterwards
PATCH bodyNickname afterwardsMeaning
{"email": "[email protected]"}"Bea"Absent: unchanged
{"nickname": null}No nicknamenull: removed
{"nickname": ""}""Empty: set to an empty string

In responses, choose one rule. A customer with no nickname can be sent without the field or with "nickname": null. Either works, but mixing them forces clients to check for both. Many APIs always include every field, using null for no value, so the response shape never changes.

Empty lists are not null. An order with no items should send "items": [], not null or nothing. A client can loop over an empty list without a special case.

Required and nullable are different questions. Required means the field must be present; nullable means its value may be null. A field can be required and nullable, as with a cancelledAt that is present on every order and null until the order is cancelled.

Why it bites. Many languages turn both absent and null into the same empty value when parsing. A server that does so cannot tell "leave the nickname" from "remove it", and either never clears it or clears it on every unrelated update.

So write down, per field, whether it is required, whether it is nullable, and what absent means in an update.