I have RESTful API built on top of a MongoDB store, so it's nice that you can store arrays. It's straightforward to create a new resource like this:
POST /users
{ items: [ 1001, 1002, 1003 ] }
But how would the HTTP endpoint for adding a new item or removing an item would look like?
Right now, I have to specify the entire array, including elements that I don't want to touch:
PATCH /users/{id}
{ name: 'Bruce Wayne', items: [ 1001, 1002 ] }
Or pass in a mongodb query directly:
PATCH /users/{id}?query[$push][items]=1003
Is there a better way to do this?
Edit:
I like how StackMob's API does it. How do I update the name
and remove an element from items
at the same time though? For example, when I'm updating a bunch of the user's details on an admin dashboard? I don't think replacing the entire array is a good idea in mongodb?
An API endpoint is a point at which an API -- the code that allows two software programs to communicate with each other -- connects with the software program. APIs work by sending requests for information from a web application or web server and receiving a response.
Deletes use the http DELETE verb. In order to delete an object you must pass the unique key of that object. For example, if you wish to delete a user , the user_id field must be present in the JSON request (other fields are ignored).
Passing a mongodb query seems like a bad idea. Depending on your backend implementation it could lead to an attacker doing bad things to your data as in SQL Injection
You can model the modification of an attribute on a resource with PUT or PATCH with some limitations:
PUT
the client is expected to send the whole representation of the resource. IT works for you but it may be cumbersome.PATCH
the client is expected to send the attributes that are intended to change, instead of the whole resource. Yet, you have to send the whole value, not just the additions or deletions of items to the value. Again it works but you are not in love with it.I think you are looking for a way to model adding and removing items to the array:
/users/:id/items
POST
to add an item to the array and DELETE
to remove from the array.It's simple and RESTful.
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