0

I am developing a REST API and I would like to allow the users to remove a field of the object through PATCH.

My idea was to use a null field on the PATCH body as a signal to remove this field of the object. Is that a good approach? Is there a better way to allow a user to remove a field from an object using a REST API?

I would like to avoid the need to PUT the entire new object.

2
  • ’I would like to avoid the need to PUT the entire new object.’ From a client perspective it’s often easier to PUT an entire object, then it is to first figure out which properties have changed and then making a separate request for each changed property. It depends on the use case ofc.
    – Rik D
    Sep 16 at 16:36
  • 1
    If you use something like JSON Patch you can describe a removal explicitly.
    – jonrsharpe
    Sep 16 at 17:22
1

My idea was to use a null field on the PATCH body as a signal to remove this field of the object. Is that a good approach?

No.

The right way to do it is to use a general purpose media type that describes the edits that you have made to the local representation of the resource, and implementing the appropriate interpreter on the server.

Here's an example using JSON Patch.

PATCH /my/data HTTP/1.1
Content-Type: application/json-patch+json

[
  { "op": "remove", "path": "/a/b/c" }
]

Here's another example of the same edit, using JSON Merge Patch

PATCH /my/data HTTP/1.1
Content-Type: application/merge-patch+json

{
  "a": {
    "b": {
      "c": null
    }
  }
}

The important idea here being that we are using the Content-Type header to describe how the patch document is to be interpreted.

Servers are expected to use an Accept-Patch header to signal the supported patch document formats.


I would like to avoid the need to PUT the entire new object.

Unless the original representation is large compared to your HTTP headers, and the representation of the patch document is much smaller, the benefits of PUT will usually outweigh the costs.

Also, there's nothing wrong with supporting both, and letting the client decide for itself which method semantics are most appropriate.

1
  • 1
    This is unnecessarily verbose and extremely complicates stuff when you are using accept headers for versioning and perhaps even routing to backends.
    – Andy
    Sep 17 at 5:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.