How to apply the PUT verb in a REST request?
I'm working on a REST server. I have an order RESOURCE.
From my understanding the PUT verb should create a new order based on the URL. My question is: How can this work if开发者_如何学C the resource is new and you don't know the ID of the new order?
I know the debate about POST vs PUT, but I'm quoting the w3 specs for PUT http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
"If the Request-URI does not point to an existing resource, and that URI is capable of being defined as a new resource by the requesting user agent, the origin server can create the resource with that URI"
In RESTful APIs, PUT
is typically used to update a resource or create one if it doesn't exist at the specified URL (i.e. the client provides the id). If the server generates the id, RESTful APIs typically use a POST
to create new resources. In the latter scenario, the generated id/url is usually returned or specified in a redirect.
Example: POST /orders/
According to W3C Both PUT
and POST
can be used for update and/or create.
The basic difference between them is how the server handles the Request-URI. PUT
URI identifies the entity and the server should't try to map it to another URL, while POST
URI can be a handler for that content. Examples:
It's OK to POST
a new order to /order
, but not a PUT
. You can update order 1 with a PUT
or POST
to /order/1
.
To put it simply POST
is for creating and PUT
is for updating. If you don't have an ID for an object because it isn't created yet, you should be using a POST
. If an object DOES exist and you just don't have the ID for it, you're going to have to search for it using a GET
of some kind.
The thing to remember is Idempotence. A PUT
(and GET
for that matter) is idempotent. Basically meaning, you can hit the same URL over and over and it shouldn't make a difference the 2nd or 3rd time (It edits the data once, and calling it again it doesn't make that change again). However a POST
is not idempotent. Meaning, you hit the same URL 3 or 4 times in a row and it's going to keep changing data (creating more and more objects). This is why a browser will warn you if you click back to a POST
url.
You say, "don't know the ID of the new order" therefore the following is not true "URI is capable of being defined as a new resource by the requesting user agent", therefore PUT is not appropriate in your scenario.
Where is the confusion? I am of course assuming the Id would be part of the URL.
精彩评论