Do you know any "best practice" to design a REST method to alter the order of a small collection?
I have a collection exposed at "GET /api/v1/items". This endpoint returns a JSON array and every item has a unique id.
I was thinking on create "PATCH /api/v1/items" and send an array of ids with the new order. But I wonder if there is any alternative or design pattern to accomplish this task properly.
Following the REST Uniform Interface constraint, the HTTP
PUT
andPATCH
methods have to stick to the standard semantics, so you can do that with either one in the following way:With
PUT
, clients can upload a whole new representation with the order they want. They will requestGET /api/v1/items
, change the order as they need, and submit it back withPUT /api/v1/items
.With
PATCH
, clients can send a diff document which performs the order change as they need. You can use a format like json-patch and clients perform the change with themove
operation and array paths.Be aware that neither of these are design patterns or best practices. They are simply how the
PUT
andPATCH
methods are supposed to work. Ideally, this should work on any RESTful application implementing theGET
,PUT
andPATCH
methods correctly for the resource at that URI, and that's the beauty of REST. If you do it the right way, you only have to do it once and clients can generalize for everyone. For instance, a client can choose to do it thePUT
way with small collections, and thePATCH
way for larger ones.Both your idea to use
PATCH
with an id array, and the answerfrom @dit suggesting to do it withPUT
aren't really RESTful because they are breaking up with the standard semantics: yours for not using a delta format, his for doing partial updates withPUT
. However, both those options can be RESTful if done withPOST
.POST
is the method to go for any action that isn't standardized by the HTTP protocol, so you can do anything you want with it, but you have to document how exactly to do it.So, it's up to you. If you are concerned at all with being RESTful and your application has long term goals -- I'm talking years or even decades -- I'd say to go for a uniform implementation of the
PUT
andPATCH
methods as suggested first. If you prefer a simple approach, use yours or dit's idea withPOST
.ok, I had a similar problem and will try to explain how I solved it.
my bike tour has about 5 stations. Every station has an unique ID and order number:
Every time if the order of single item was changed (drag and drop) i send REST request to my webservice.
Suppose we want to move the station uid=3 one position down. Station with uid=3 goes down and station with uid=4 goes up. So my PUT request looks like this:
Now, on the server side I just have to find items affected by this move down action and update their order in my database. My REST webservice sends
OK
if update was successful.In my case it was not necessary to send the new sorted list, cause my UI was always changed by drag and drop action.