Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REST API - To PUT or to POST? [duplicate]

Tags:

rest

Possible Duplicate:
PUT vs POST in REST

I know this has been discussed a lot and although I kind of get it, I don't completely get it. I think if someone could answer this in relation to the following example it would make it easy to understand.

Create new user - add a new user to a database sending Username, Password, Email. PUT or POST?

I think maybe PUT as I don't want to have duplicate users and PUT is like deleting and replacing. However, I have checks that avoid a user being added twice so maybe I should use POST?

Update user - change email or password. PUT or POST?

I could use URI api/update/my_username and then send new email via the body so should this be PUT? I could also send it all in the URI e.g. api/update/my_username/email/[email protected]

like image 540
Paul Benbow Avatar asked Jul 19 '12 10:07

Paul Benbow


2 Answers

Create - POST, update - PUT, delete - DELETE.

For better understanding of HTTP Verbs usage look at RFC https://www.rfc-editor.org/rfc/rfc2616

Also PUT request can create entities but then response code should be 201 created instead 200 OK and 204 No Content. But it's up to you either allow/implement such behaviour or not.

like image 91
Regfor Avatar answered Nov 15 '22 07:11

Regfor


The key guide is whether the operation is idempotent, i.e., what happens if you repeat it. If the same thing overall happens (ignoring logs, last change times, and other fripperies) whether you do the request once, twice or 20 times, it is idempotent and should be a PUT. If the number of times you do it matters, use POST.

Creation is often non-idempotent because you typically issue the user an ID, but it doesn't have to be like that (e.g., if the caller specifies the ID). Updating is often idempotent as changing data fields to their current values is often an effective no-op in practice.

like image 45
Donal Fellows Avatar answered Nov 15 '22 08:11

Donal Fellows