Can I PUT without an ID?

旧巷老猫 提交于 2019-12-05 13:14:48
Tatsuyuki Ishi

No. PUT means "create or update", and should come with an explicit ID. POST is suitable for creating something new.

See also: PUT vs POST in REST

Regarding the actual title of the question I somehow disagree with the accepted answer given by @TatsuyukiIshi. PUTs semantics are: Replace the content currently obtainable at the given URI with the payload contained in the request. If a resource can be identified without an ID, i.e. there only ever may exist one of its kind, it IS possible to address an update without specifying an ID as the ID of the "singleton resource" is already implicitly given in the endpoint itself. Though, I have to admit that this is rarely the case.

Such a case may be a clipboard like resource where you can put arbitrary content to and retrieve it later on. Sure, you could also use POST, though the semantics of the body received with the POST request are less clear. Also POST is not idempotent in contrary to PUT operations.

Using something like PUT /api/messages, however, would usually mean replace all messages with the content sent with the request which might not be what you really want. Usually you only want to modify a single resource at once and hence use an accompanying ID that identifies that specific resource.

In regards to the actual content of the question, uploading a file via POST is the common practice. On a successful upload you will return a 201 Created response that contains a Location HTTP header that points to the generated resource. The behavior of a service processing content received via POST requests is totaly up to the service implementor. Therefore you could create a new resource, perform some backing task without any actual resource creation or something other (even updating is not forbidden by the specification).

Too late for you, but I was with this same question and found a lot of wrong information, so I will let here what a found.

There are 2 RFC that rules RESTful, the one about this question is RFC 7231, in that you will find:

The PUT method requests that the state of the target resource be created or replaced with the state defined by the representation enclosed in the request message payload.

So you can't send a PUT without the ID.

A lot of RESTful API send a POST even on updates, that's wrong too by that same RFC, so you should always send the ID to create it with PUT, or should use POST to create and PUT to update, but remember that POST should always create, in another words, you will duplicate your file if you don't look for it first with GET.

For more information: https://tools.ietf.org/html/rfc7231#section-4.3.3

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!