REST API – Handling Omitted Properties in POST Requests

api-designhttp-requestrestsemantics

Given the following scenario:

  1. Teacher entity

    {  
    "id": "1234",  
    "name": "Mr. Didactic",  
    "Subject": "History",  
    "Classroom": "1A"  
    }
    
  2. REST API endpoint:

    /teacher/id/1234
    

Let's say I submit a POST (update) request to the endpoint with this request body:

{  
"id": "1234",  
"name": "Mr. Didactic",  
"Subject": "History"
}

How should that be handled/interpreted? Is Classroom being requested to be set to null/empty?

Or is it untouched, i.e. don't do anything to Classroom, it's not part of the request?

Or is there some other way of interpreting this? What's expected, or are the best practices here?

Best Answer

For an update (POST) request, a field that is omitted should not be changed. To clear a field from it's value, it should be mentioned in the request with the value null or a normal value to change the value completely.
In your example, Classroom will keep the value 1A.

For a replace document (PUT) request, all the fields will be cleared and replaced with what is inside the request. So when a field is omitted, it will be cleared.
In you example, when you send a PUT request, Classroom will be null.

When using POST as a create request, the omitted fields will not be set, so Classroom stays null.

This is at least the way that is specified in the jsonapi.org specification (a specification for JSON responses on REST services):

If a request does not include all of the attributes for a resource, the server MUST interpret the missing attributes as if they were included with their current values. The server MUST NOT interpret missing attributes as null values.

Other specifications, like OData, describe the same behaviour. But as long as you document the implemented behaviour, it is your choice.