Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RESTful API endpoint for adding/removing array elements?

Tags:

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?

like image 963
thatmarvin Avatar asked Mar 12 '13 19:03

thatmarvin


People also ask

What are RESTful API endpoints?

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.

How do I remove an item from an API?

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).


1 Answers

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:

  • When using PUT the client is expected to send the whole representation of the resource. IT works for you but it may be cumbersome.
  • When using 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:

  1. I would model the array as a resource on its own: /users/:id/items
  2. Accept POSTto add an item to the array and DELETE to remove from the array.

It's simple and RESTful.

like image 148
Daniel Cerecedo Avatar answered Nov 06 '22 14:11

Daniel Cerecedo