-1

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?

Melkor
  • 243
  • 2
  • 14
  • See https://tools.ietf.org/html/rfc7231#section-4.3.4; if changing the *location* of a resource via PUT would mean a subsequent GET of the same resource would 404 (or, worse, succeed but for a different resource), that doesn't seem correct semantically. If you got a 3xx that might be OK. – jonrsharpe Dec 15 '19 at 16:43
  • yeah I totally agree with you, but thats the point of my question. How can I enable the user to change the username, while still following the REST principles and not using a surrogate key? – Melkor Dec 15 '19 at 16:47

1 Answers1

1

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.

Evert
  • 93,428
  • 18
  • 118
  • 189
  • could you provide a link to more information about MOVE method? I can't really find anything in the spec. Thanks for your correction about idempotence btw! – Melkor Dec 15 '19 at 23:19
  • 1
    @Melkor here's the official list of HTTP methods, along with where they are defined: https://www.iana.org/assignments/http-methods/http-methods.xhtml . MOVE was added in the WebDAV extension, but there's nothing really about it that prevents it from being used in other HTTP applications. – Evert Dec 15 '19 at 23:34