Let's say I'm creating a RESTful interface, and I want to upload a resource using PUT
to /resources/{id}
. But I only want to be upload the thing if it hasn't been uploaded before.
I realize that PUT
should be idempotent, so if I PUT
something twice to the same URL it should succeed both times, right?
I also understand that I could use HEAD
on an existing resource, and then use an ETag
to in my PUT
to ensure that the resource hasn't been modified since I last checked.
But how can I ensure that I only upload a thing if the thing doesn't already exist? That is, how can I make sure I don't step on someone else's thing?
If the target resource does not have a current representation and the PUT successfully creates one, then the origin server MUST inform the user agent by sending a 201 (Created) response.
5) Mention whether you can use GET request instead of PUT to create a resource? No, you are not supposed to use PUT for GET. GET operations should only have view rights, while PUT resource is used for updating a data.
The PUT method requests that the state of the target resource be created or replaced with the state defined by the representation enclosed in the request message payload. So you can't send a PUT without the ID.
So both POST/PUT can be used for insert/update (both submit data). It's up to the dev how they want to use - some like to map CRUD to the methods - others just POST or PUT for everything depending on idempotence.
I realize that PUT should be idempotent, so if I PUT something twice to the same URL it should succeed both times right?
Correct.
But how can I ensure that I only upload a thing if the thing doesn't already exist? That is, how can I make sure I don't step on someone else's thing?
Don't use a HEAD call. Make a PUT call using the header If-None-Match: *
. This will instruct the server to only perform the operation if no current entity exists, as detailed in RFC 2616 paragraph 3.
See http://greenbytes.de/tech/webdav/rfc7232.html#rfc.section.3.2.p.7:
"If-None-Match can also be used with a value of "*" to prevent an unsafe request method (e.g., PUT) from inadvertently modifying an existing representation of the target resource when the client believes that the resource does not have a current representation (Section 4.2.1 of [RFC7231]). This is a variation on the "lost update" problem that might arise if more than one client attempts to create an initial representation for the target resource."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With