Search code examples
node.jsrestapistandards

Should REST api PUT accept a request with a single edited property and the id of the document?


Or should the client send every time every property even if they were not edited?

So imagine on the server I have stored in my DB the following document:

{
  _id: "1",
  name: "Mario",
  surname: "Rossi"
}

Now imagine the client wants to update JUST the name. Should this PUT request be acceptable?

{
  _id: "1",
  name: "Giorgio"
}

Or should the client send all properties?

{
  _id: "1",
  name: "Giorgio",
  surname: "Rossi"
}

It seems like partial edits can save some bandwidth and it does not really make sense to send extra data, but I'm not sure about what's the standard here. Thanks!


Solution

  • The representation you send with a PUT request should be the same that you expect to get back from a GET request.

    A successful PUT of a given representation would suggest that a subsequent GET on that same target resource will result in an equivalent representation being sent in a 200 (OK) response. -- RFC 7231

    In other words, the representation included in the body of a PUT request is expected to be the complete representation.

    See also the introduction for HTTP Patch:

    The existing HTTP PUT method only allows a complete replacement of a document.

    Roy Fielding, writing in 2012:

    When a server that implemented PUT prior to the introduction of Content-Range received a partial content body that included such a range, they would replace the entire resource representation with the partial body. That is how PUT was defined to work.... the introduction of partial PUT would only be possible with a strong coupling between client and origin server implementations, which violates the design of the HTTP.

    There are cases where the representation is very large (much larger than the HTTP headers), and the changes we are making are small, where it would be sensible to send a representation of the changes, rather than the complete representation.

    But PUT isn't the method we use in that case, because the semantics are wrong. Our standards compliant choices here are to end the entire (revised) representation with PUT, or a representation of the changes in a patch-document with PATCH.