开发者

Correct HTTP method for RESTful create-or-update?

开发者 https://www.devze.com 2023-04-02 12:20 出处:网络
I\'m creating a RESTful web service that allows me to import documents by name. I would import a document using a path like this:

I'm creating a RESTful web service that allows me to import documents by name. I would import a document using a path like this:

/documents/frequently-ask开发者_开发技巧ed-questions

If the document doesn't already exist, it would create a new one; otherwise, it would simply overwrite the existing document.

The question I have is whether this is a wrongheaded endpoint for a RESTful service. Normally I'd use POSTs for creates and PUTs for updates. Here it's not known in advance whether the document already exists. If this is reasonable, then what's the best HTTP method? If it's not correct, then what's a better approach?


The HTTP 1.1 specification says for POST:

9.5 POST

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 for PUT:

9.6 PUT

The PUT method requests that the enclosed entity be stored under the supplied Request-URI.

Given that, and the fact that PUT is idempotent and POST is not, PUT seems the logical choice here for both your create and update.

Source: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.2


Here is my salt test for using POST vs PUT:

The general idea is POST is used for creating, and PUT is used for updating. But in the create-or-update scenario, they both apply. The key here is you already know the resource's ID.

So...

If the URL contains the document's identifier, use PUT, otherwise use POST.

In your case, the identifier is known, and in the URL, so use PUT.

0

精彩评论

暂无评论...
验证码 换一张
取 消