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?
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.
PUT HTTP Request The PUT method requests that the enclosed entity be stored under the supplied URI. If the URI refers to an already existing resource, it is modified and if the URI does not point to an existing resource, then the server can create the resource with that URI.
Regarding the actual title of the question I somehow disagree with the accepted answer given by @TatsuyukiIshi. PUT
s 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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With