Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RESTful PUT if not exists?

Tags:

rest

http

put

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?

like image 555
Garret Wilson Avatar asked Jun 18 '14 14:06

Garret Wilson


People also ask

Does Put create if not exist?

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.

Can we use GET request instead of put to create a resource?

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.

Does HTTP PUT require an ID?

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.

Can we use Put instead of POST?

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.


2 Answers

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.

like image 85
Eric Stein Avatar answered Sep 24 '22 19:09

Eric Stein


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."

like image 36
Julian Reschke Avatar answered Sep 23 '22 19:09

Julian Reschke