Search code examples
resthttp-headersputhttp-status-codeshttp-method

REST Response after updating a resource resulting in a location change


Let's say I have a user resource (/users/{username}) and the client uses PUT to update the username. In this case the location of the resource changes (because username is the ID).

That's not idempotent, because you can't perform the same request a second time and get the same result. Does that mean I have to use POST instead?

Additionally I don't know with which status code to reply. 201 (created) seems not correct, because the resource was not created, just updated. On the other hand you have to give the new location to the client.

Whats the best practice for performing an update resulting in a location change? Probably to forbid it?


Solution

  • Having stable urls for resources is a good thing. If routine changes to your resource change their location, that might also be bad for other things pointing to those locations.. especially after a change there's a 404, and not a 301 or 308 status code.

    The most elegant way to change the URI of a resource might perhaps be the MOVE HTTP method:

    MOVE /user/foo HTTP/1.1
    Destination: /user/bar
    

    However, with all that being said a PUT intially returning a 2xx code and immediately after a 404 does not violate the idempotence constraint of PUT.

    Despite that the second request was a failure, the state of the server after the first PUT request will still be the same after the second PUT request.

    It's not a requirement for 2 identical idempotent HTTP requests to return the same status.