I'm working on a REST API for a list of navigation menu items, pretty much for learning purposes. Until this point everything in the API was pretty straightforward because I only had to modify single items via the classic /collection/{id}
stuff.
But now I want to change the order of the list items stored in the order
field of my database and of course I don't want to do one request for each menu item.
So what would be an appropriate way / a common best practice of doing this?
I could imagine sending a PUT
request to /collection
with the id-order key-value pairs in the sent data but Laravel (which I use to build the API) does not allow this. I certainly could play around that restriction but I guess there are sensible reasons that this is not allowed.
Another idea would be to send a PUT
request to /collection/{ids}
with a comma-separated list of IDs but for that I also would have to send a key-value list of the IDs and their order value which seems pretty redundant and due to that also a little dirty.
So what would actually be the best approach?
To use the REST API to update existing model objects, complete one of the following two methods: Use the model object resource representing the existing object and the HTTP PUT method, passing the new object data in the body of the request.
Use the POST method when:you do not have a unique identifier of the resource that you are going to send. you are trying to send a bunch of resources in one API call, where the state of few/all resources is already persisted on the server.
Order matters only when two routes would handle both the same path and the same method. So, since app. post() and app. get() each only intercept different methods, they don't compete in any way and thus their relative ordering to each other does not matter.
As a RESTful API HTTP method, PUT is the most common way to update resource information. It's possible to create a resource with a PUT method, but this approach carries the risk of creating resources by accident, as noted above.
I suggest that you define a new route with a resource path: /collection/reorder.
This allows to send it using the method POST
the list of elements with their new positions. The content will look like something like that:
{
"element1": 4,
"element2": 1,
(...)
}
"element1" is the identifier of an element and the corresponding value, its new order.
You can notice that the format of data you need to send to this method can be depend on the tool you use in the UI to reorder the list (for example, for drag'n drop).
Hope it helps. Thierry
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