POST array of objects to REST API

api, arrays, json, post, rest

Solution

There is no need to wrap the array in another object with a `data` property. The array by itself is valid JSON:

post_params = JSON.stringify([ { 'name' : 'Alice', 'age' : 15 },
                               { 'name' : 'Bob',   'age' : 20 },
                                  ...
                             ]);
post(url, post_params);

Just make sure your API expects this array as well.

Problem

I'm designing REST API that should be able to accept array of objects, say ``` [ { 'name': 'Alice', 'age': 15 }, { 'name': 'Bob', 'age': 20 }, ... ] ``` Indeed, the API could have a method for accepting single object, which would be called in cycle. However, for performance reasons, I wish to POST multiple objects in one request. What is the most elegant way of doing so? So far my only idea is to use JSON, such as: ``` post_params = { 'data' : to_json_string([ { 'name' : 'Alice', 'age' : 15 }, { 'name' : 'Bob', 'age' : 20 }, ... ]) }; post(url, post_params); ``` Is this OK, or should I use some completely different approach?

Original source