1

I would like to know the usage scenario of POST vs PUT in a WebAPI . I know the basic concepts that POST is for creating resource and PUT is for updating resource but not able to fully understand why we need a PUT over a POST.

I have 2 WebAPI methods which creates/updates data to my SQL store 1. CreateUser(UserDto) 2. UpdateUser(UserDto)

UserDto contains userId, username and email.

I can use POST for both CreateUser and UpdateUser methods which creates and updates user to my store.

Then what is the real advantage of using POST for CreateUser and PUT for updateuser? Is it just a standard/convention?

Thank you

Greg444
  • 13
  • 2
  • 1
    The difference is that PUT is *idempotent* by design. Check this tag for more information: http://stackoverflow.com/questions/tagged/idempotent+put – Aurélien Bénel Mar 17 '17 at 16:38
  • And if PUT is idempotent by design it is because, according to HTTP specifications, its URI is the identifier of the object to be created or updated (contrary to POST). – Aurélien Bénel Mar 17 '17 at 16:46
  • Possible duplicate of *a lot* of questions: http://stackoverflow.com/questions/tagged/post+put+rest – Aurélien Bénel Mar 17 '17 at 16:50

2 Answers2

0

POST always creates something new. PUT updates a existing thing. It is a convention.

You should have:

POST /users : to create a new user. The payload should not include the ID

PUT /user/(id) : to replace a user DTO with the data in the payload. Again, the payload should not contain an user id

PATCH /user/(id): to update specific members of the user, but the id.

It is a design convention, like software design patterns, to make it easy to communicate and understand by whoever has to consume the API.

vtortola
  • 34,709
  • 29
  • 161
  • 263
  • 1
    "POST always creates something new": not necessarily (e.g. if the payload contains the ID). It depends on the API (contrary to PUT which is always idempotent because the object'sID is the URI). – Aurélien Bénel Mar 17 '17 at 16:49
  • Should not that cause a HTTP 409? http://stackoverflow.com/questions/3825990/http-response-code-for-post-when-resource-already-exists – vtortola Mar 17 '17 at 17:04
  • Sending a 409 code can be indeed a way to implement idempotency. By doing this, "the side-effects [in the store] of N > 0 identical requests are the same as for a single request". – Aurélien Bénel Mar 19 '17 at 21:09
0

POST is usually used to add a new resource into collection of resources. Like this: POST /users. This operation is NOT idempotent and it will have a side effect at each call.

While PUT is usually used with a replace semantic and you know the exact resource which you want to replace. Like this: PUT /users/1. This operation is idempotent and it will not have any side effects on subsequent calls.