21

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?

Tregoreg
  • 18,872
  • 15
  • 48
  • 69

2 Answers2

27

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.

Adam Liechty
  • 355
  • 4
  • 12
11

Basically, the answer I was looking for was:

  1. There is no need to use Content-Type: application/x-www-form-urlencoded which is standard in web; instead, Content-Type: application/json should be used,
  2. The whole HTTP request then looks as follows:

    POST /whatever HTTP/1.1
    Host: api.example.com
    Content-Type: application/json
    
    [
      {
        'name': 'Alice',
        'age': 15
      },
      {
        'name': 'Bob',
        'age': 20
      },
      ...
    ]
    
Tregoreg
  • 18,872
  • 15
  • 48
  • 69
  • 11
    Your answer is basically a copy of @Adam's answer, which is right based on the question. The information you have added to your answer about content type was not in your original question. – Japheth Ongeri - inkalimeva Jun 15 '16 at 13:18
  • 6
    @inkalimeva The thing is that the whole question is ill-posed. At the time of asking, I was absolutely inexperienced with REST a didn't know what I want to ask. I was stuck in good-old `application/x-www-form-urlencoded` and I thought that's the only possible way of submitting the data, formatted as `key1=value1&key2=value2`. If I knew I could just use `Content-Type: application/json` and submit JSON directly in the body, then the question would not make any sense, would it? If my past myself found my current answer, it would lead him directly to the solution and the missing knowledge. – Tregoreg Jun 18 '16 at 19:28