Currently developing a REST API, with a suite of endpoint functions which update the "state" of a particular resource.
I am using POST to create the initial resource and then updating the state using PUT - Is PUT the correct method to be using?
The state updates are being logged in a journal, so to avoid someone updating the state with the same value multiple times, I wish to put some business logic in that avoid two repeat entries of the same state. If someone attempts to call the same function twice, lets say "CancelResource()" - should I return a 200 success on the second call, and just not make an update, or would it be better to send some sort of error response?
I was considering returning a 405 "method not allowed" but this feels a little harsh. I also don't know that 200 would be very useful for the client.
CodePudding user response:
PUT
is appropriate for updates, and PUT
should be idempotent. This means that if you do the exact same PUT
request twice in a row, the server state should be no different from if you only did it once.
This is useful in for example unreliable connections. Clients can just repeat the request if it failed, without having to worry that the server somehow did receive the request and process it.
So if you have a means to detect identical requests, ignoring the second and return a 200 OK
on both that's an excellent way to handle this.
CodePudding user response:
Is PUT the correct method to be using?
PUT is appropriate if the body of the request is being proposed as a replacement representation for the target resource.
A successful PUT of a given representation would suggest that a subsequent GET on that same target resource will result in an equivalent representation being sent in a 200 (OK) response. -- RFC 9110
Think "save file" -- PUT is the HTTP method we would use if we were trying to upload content to a web server.
should I return a 200 success on the second call, and just not make an update,
Probably. For 2xx vs 4xx, you should be thinking about the effect of the status code on the caches that are involved. See RFC 9111.
Note that RFC 9110 specifically calls out this choice in the discussion of the If-Match conditional header:
if the request is a state-changing operation that appears to have already been applied to the selected representation, the origin server MAY respond with a 2xx (Successful) status code (i.e., the change requested by the user agent has already succeeded, but the user agent might not be aware of it, perhaps because the prior response was lost or an equivalent change was made by some other user agent).
CodePudding user response:
PUT is idempotent, it does not make sense to deny a PUT request, because nothing changed. Just send 200 ok and don't change anything.