Search code examples
node.jsmongodbrestrestful-url

Should send null or empty string value via body?


Should we send a null or empty string value on request ?

I mean we have an optional value and it had a value currently. If use want to delete value of that optional field, should API understand null or empty is delete value ?

Ex:

{
  name: { type: String, required: true },
  phone: { type: String, required: false }
}

In database:

{
  name: "Alex",
  phone: "012-333.222"
}

And now, use want to delete their phone number Should we define looks like:

PUT /users/user-id-1
{
  phone: null
}

Seems it's a bad convention


Solution

  • Should we send a null or empty string value on request ?

    REST doesn't care; which is to say that it tells us to use self descriptive messages to transfer documents over a network, but it doesn't tell us what the representations of the documents should be.

    Where you want to be looking instead is at message schema definitions, and in particular designing your schema in such a way that it can be extended in backwards compatible ways. The XML community spent a lot of time exploring those ideas; Orchard 2004 might be a good starting point.


    In HTTP, the basic mechanism for describing a change to a resource is to use a PUT command with a copy of the new representation. So a request would probably look like:

    PUT /users/user-id-1
    Content-Type: application/json
    
    {
      name: "Alex",
      phone: null
    }
    

    If your schema is defined in such a way that the phone field is optional, and that optional and null are equivalent (as opposed to some other implied value), then you might equivalently use:

    PUT /users/user-id-1
    Content-Type: application/json
    
    {
      name: "Alex"
    }
    

    In cases where the representation is very big, and the changes you are making are small, you might want to support PATCH.

    PATCH /users/user-id-1
    Content-Type: application/merge-patch+json
    
    {
      phone: null
    }
    

    Note that the HTTP PATCH specification includes the Allow-Patch which allows clients to discover which patch representations a server supports for a resource.