32

According to REST style, it's generally assumed that HTTP POST, GET, PUT, and DELETE methods should be used for CREATE, READ, UPDATE and DELETE (CRUD) operations.

But if we stick to the HTTP method definitions, it might not be so clear.

In this article it's explained that:

In a nutshell: use PUT if and only if you know both the URL where the resource will live, and the entirety of the contents of the resource. Otherwise, use POST.

Mainly because

PUT is a much more restrictive verb. It takes a complete resource and stores it at the given URL. If there was a resource there previously, it is replaced; if not, a new one is created. These properties support idempotence, which a naive create or update operation might not. I suspect this may be why PUT is defined the way it is; it's an idempotent operation which allows the client to send information to the server.

In my case I usually issue updates passing all the resource data, so I could use PUT for updates, but every time I issue an update I save a LastUser and LastUpdate column, with the user id that made the modification and the time of the operation.

I'd like to know your opinion, because strictly speaking those two columns are not part of the resource, but they do prevent the operation from being idempotent.

xlm
  • 6,854
  • 14
  • 53
  • 55
opensas
  • 60,462
  • 79
  • 252
  • 386
  • How do you represent `LastUser` and `LastUpdate` - are they a part of your resource representation (i.e. nodes in XML)? – MicE Apr 16 '11 at 17:01
  • no, they don't even exists when issiung an update, but I return them when querying with a get.... so I make a PUT, and then a GET, and I get the lastUpdate time, I issue again the same PUT, and another GET yields a different lastUpdate... – opensas Apr 16 '11 at 17:11
  • Ok, thanks for confirming - see my answer below for an alternative take on the problem. – MicE Apr 16 '11 at 19:10

4 Answers4

32

Ignoring the comment about the REST style mapping CRUD to the HTTP methods, this is an excellent question.

The answer to your question is, yes you are free to use PUT in this scenario even though there are some elements of the resource that are updated by the server in a non-idempotent manner. Unfortunately, the reasoning behind the answer is quite vague. The important thing, is to understand what was the intent of the client request. The client intended to completely replace the contents of resource with the values passed. The client is not responsible for the server doing other operations and therefore the semantics of the HTTP method are not violated.

This is the reasoning that is used to allow a server to update a page counter when you do a GET operation. The client didn't ask for an update therefore the GET is safe even though the server chose to make an update.

The whole, complete resource versus partial resource debate has finally been spelled out in an update to the HTTP spec

An origin server SHOULD reject any PUT request that contains a Content-Range header field, since it might be misinterpreted as partial content (or might be partial content that is being mistakenly PUT as a full representation). Partial content updates are possible by targeting a separately identified resource with state that overlaps a portion of the larger resource, or by using a different method that has been specifically defined for partial updates (for example, the PATCH method defined in [RFC5789]).

So, what we are supposed to do is now clear. What is not so clear is why there exists this constraint on only being allowed to send full responses. That question has been asked and IMHO remains unanswered in this thread on rest-discuss.

Community
  • 1
  • 1
Darrel Miller
  • 139,164
  • 32
  • 194
  • 243
  • Yes, I agree. Still, using PATCH or Content-Range headers does not feel right, since the client is attempting to modify the whole resource (at least the parts which the client is allowed to modify). See my answer for a different take on the problem. I know that it's also not bulletproof, but it tries to mitigate the problem at least a bit. – MicE Apr 16 '11 at 19:13
  • 2
    http://williamdurand.fr/2014/02/14/please-do-not-patch-like-an-idiot/ - I'm not calling anyone an idiot but it's a useful read. – backdesk Jan 11 '16 at 13:03
  • Agreed with the answer. Notably that RFC7231 also has a relevant part on the _"elements of the resource that are updated by the server"_ (BTW, it's one of RFCs that obsolete the '99 RFC 2616).It mentions [here](https://tools.ietf.org/html/rfc7231#section-4.3.4) that server can have `transformation applied to the body` and even describes a mechanism for client that `allows a user agent to know when the representation body it has in memory remains current`, i.e.: the server `MUST NOT send ... an ETag or Last-Modified ... unless the request's representation was saved without any transformation`. – Slawomir Brzezinski Nov 08 '20 at 19:57
9

As LastUser and LastUpdate are not modifiable by the client, I'd remove them from the representation of your resource altogether. Let me explain my reasoning with an example.

Let's say that our typical example API will return the following representation to the client when asked to provide a single resource:

GET /example/123

<?xml version="1.0" encoding="UTF-8" ?>
<example>
    <id>123</id>
    <lorem>ipsum</lorem>
    <dolor>sit amet</dolor>
    <lastUser uri="/user/321">321</lastUser>
    <lastUpdate>2011-04-16 20:00:00 GMT</lastUpdate>
</example>

If a client wants to modify the resource, it would presumably take the whole representation and send it back to the API.

PUT /example/123

<?xml version="1.0" encoding="UTF-8" ?>
<example>
    <id>123</id>
    <lorem>foobar</lorem>
    <dolor>foobaz</dolor>
    <lastUser>322</lastUser>
    <lastUpdate>2011-04-16 20:46:15 GMT+2</lastUpdate>
</example>

Since the API generates values for lastUser and lastUpdate automatically and cannot accept data provided by the client, the most appropriate response would be 400 Bad Request or 403 Forbidden (since the client cannot modify these values).

If we want to be compliant with REST and send a full representation of the resource when doing a PUT request, we need to remove lastUser and lastUpdate from the representation of the resource. This will allow clients to send the full entity via PUT:

PUT /example/123

<?xml version="1.0" encoding="UTF-8" ?>
<example>
    <id>123</id>
    <lorem>foobar</lorem>
    <dolor>foobaz</dolor>
</example>

The server would accept a full representation now that it doesn't contain lastUpdate and lastUser.

The question that remains is how to provide clients with access to lastUpdate and lastUser. If they don't need it (and these fields are required just internally by the API), we are fine and our solution is perfectly RESTful. If however clients need access to this data, the cleanest approach would be to use HTTP headers:

GET /example/123

...
Last-Modified: Sat, 16 Apr 2011 18:46:15 GMT
X-Last-User: /user/322
...

<?xml version="1.0" encoding="UTF-8" ?>
<example>
    <id>123</id>
    <lorem>foobar</lorem>
    <dolor>foobaz</dolor>
</example>

Using a custom HTTP header is not ideal because user agents need to be taught on how to read it. If we want to provide clients with access to the same data in a more easier way, the only thing that we can do is to put the data into the representation, and we are facing the same problem as in your original question. I would at least try to mitigate it somehow. If the content type used by the API is XML, we can put the data into node attributes instead of exposing them directly as node values, i.e.:

GET /example/123

...
Last-Modified: Sat, 16 Apr 2011 18:46:15 GMT
...

<?xml version="1.0" encoding="UTF-8" ?>
<example last-update="2011-04-16 18:46:15 GMT" last-user="/user/322">
    <id>123</id>
    <lorem>foobar</lorem>
    <dolor>foobaz</dolor>
</example>

This way we'll at least avoid the problem where a client would attempt to submit all XML nodes in a follow-up PUT request. This won't work with JSON, and the solution is still a bit on the edge of idempotency (since the API would still have to ignore the XML attributes when processing the request).

Even better, as Jonah pointed out in the comments, if clients need access to lastUser and lastUpdate, these can be exposed as a new resource, linked from the original one e.g. as follows:

GET /example/123

<?xml version="1.0" encoding="UTF-8" ?>
<example>
    <id>123</id>
    <lorem>foobar</lorem>
    <dolor>foobaz</dolor>
    <lastUpdateUri>/example/123/last-update</lastUpdateUri>
</example>

... and then:

GET /example/123/last-update

<?xml version="1.0" encoding="UTF-8" ?>
<lastUpdate>
    <resourceUri>/example/123</resourceUri>
    <updatedBy uri="/user/321">321</updatedBy>
    <updatedAt>2011-04-16 20:00:00 GMT</updatedAt>
</lastUpdate>

(The above can be also nicely expanded to provide a full audit log with individual changes, providing a resource changelog is available.)

Please note:
I agree with Darrel Miller's take on the question, but I wanted to provide a different approach on top of it. Note that this approach is not backed-up by any standards/RFCs/etc, it's just a different take on the problem.

Community
  • 1
  • 1
MicE
  • 5,038
  • 2
  • 29
  • 26
  • Thanks for the alternative approach. Using a 'last modified' header seems like a pretty good idea - especially when it comes to caching or rejecting outdated updates (i.e. resources that have been edited by someone else while you were busy changing them). Thoughts? – backdesk Jan 11 '16 at 13:06
  • 1
    why not expose it at a new endpoint? after all, as you've argued convincingly, it is a separate concept from the original resource: `example/123/lastUpdate` – Jonah Jul 03 '16 at 14:02
  • @Jonah - that is an excellent point, thank you. I updated the answer to incorporate it. (Note that e.g. URIs in the edit may be more suitable as XML node attributes. The current format should allow a more direct translation to JSON when needed.) – MicE Jul 03 '16 at 14:26
  • Re _"this approach is not backed-up by any standards/RFCs"_. **Good news** @MicE. It actually is backed by RFCs. The 2014's RFC 7231 (one of RFCs that obsolete the 1999's RFC 2616) mentions [here](https://tools.ietf.org/html/rfc7231#section-4.3.4) that server can have `transformation applied to the body`. There's even a mechanism for client that `allows a user agent to know when the representation body it has in memory remains current`, which is: the server `MUST NOT send ... an ETag or Last-Modified ... unless the request's representation was saved without any transformation`. – Slawomir Brzezinski Nov 08 '20 at 19:45
5

The disadvantage of using PUT to create resources is that the client has to provide the unique ID that represents the object it is creating. While it usually possible for the client to generate this unique ID, most application designers prefer that their servers (usually through their databases) create this ID. In most cases we want our server to control the generation of resource IDs. So what do we do? We can switch to using POST instead of PUT.

So:

Put = UPDATE

Post = INSERT

Hopefully, this helps for your specific case.

Cristian Boariu
  • 9,603
  • 14
  • 91
  • 162
  • well, I'm talking about an update in which I know the id... I'm not talking about an insert... – opensas Apr 16 '11 at 17:12
  • That is certainly an argument for reserving `PUT` for updates exclusively, but [rfc7231](https://tools.ietf.org/html/rfc7231#section-4.3.4) does formally allow it, so I think that decision should be made on a per-API basis. – Shadoninja Jan 30 '20 at 18:49
0

The HTTP methods POST and PUT aren't the HTTP equivalent of the CRUD's create and update. They both serve a different purpose. It's quite possible, valid and even preferred in some occasions, to use PUT to create resources, or use POST to update resources.

Use PUT when you can update a resource completely through a specific resource. For instance, if you know that an article resides at http://example.org/article/1234, you can PUT a new resource representation of this article directly through a PUT on this URL.

If you do not know the actual resource location, for instance, when you add a new article, but do not have any idea where to store it, you can POST it to an URL, and let the server decide the actual URL.

Anil
  • 595
  • 1
  • 5
  • 15