Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
565 views
in Technique[技术] by (71.8m points)

rest - Can I PUT without an ID?

I'm designing an API Rest service that allows the user to upload a file to the server.

I'm thinking this is a PUT request and it would go to server/resource/ID and have the file as base64 in the json request body.

My question is regarding this ID. In my head, I'm passing the file to the server and the server should be in charge of storing that file and generating a unique ID to retrieve it later, and then return this ID to the client with an ok status.

So I'm thinking about doing that, sending it to server/resource, without the ID, but is this ok or is it bad design?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...