Home > Point2 - Technical > Should I use PUT or POST for a CREATE operation in REST?

Should I use PUT or POST for a CREATE operation in REST?

March 16, 2009

POST is for CREATE, and PUT is for UPDATE and CREATE. Ok, they both allow CREATE, how should we choose to use PUT or POST for a CREATE? Let’s say we have an animal adoption service. We have /animals to give us a list of all the animals for adoption. Let’s say we allow the user to create a category to group the animals together, such as /animals/dogs/ to list all the dogs for adoptions. Meanwhile, /animals/dogs/{id_of_a_dog} will give us the details of a dog for adoption. Now, we want to create a new category “cats”, which will give us /animals/cats. We want to also be able to add a cat for adoption. Should it be PUT or POST?

The Method Definitions of HTTP says that “The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line.” And “The PUT method requests that the enclosed entity be stored under the supplied Request-URI.” The document also mentioned an important point “Methods can also have the property of ‘idempotence’ in that (aside from error or expiration issues) the side-effects of N > 0 identical requests is the same as for a single request. The methods GET, HEAD, PUT and DELETE share this property.”

In other words (plain English), we need to ask the following question:

  1. Does the user know the URI? Do we allow them to derive and decide the URI for the object to be created?
  2. What is the effect of the call to be executed twice? Is there no duplicated object created?

If the answer to both questions are true, then we should use PUT to create the categories, which means that we will PUT the request to the desired URI (animals/cats).

If the answer to both questions are false, then we should use POST to create (in this case the cat for adoption), which means that we will POST the request to the parent URI (animals/cats), in which case the response shall give us a new URL (e.g. http://somehost/animal/cats/{id_of_the_cat} ) to identify the cat that we have just created. Executing the POST again with the same request will end up creating an entry for the second cat to be adopted.

Of course, rules can be bent under certain circumstances, but we should remember “the principle of Least Astonishment” as mentioned by Scott Meyers in his  “Better Software – no matter what” talk given at SDWest, which is to strive to maximize the likelihood that user expectations about an interface are correct.

By: Nyik San Ting

Advertisements
  1. March 17, 2009 at 11:42 AM

    I have never been able to find a straight-forward answer to this puzzling question so any attempts at using the correct method have simply been guesses. Thank you for the clarification!

  1. No trackbacks yet.
Comments are closed.
%d bloggers like this: