Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POST array of objects to REST API

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?

like image 815
Tregoreg Avatar asked Jul 27 '13 15:07

Tregoreg


People also ask

How do I post an array in API?

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

Can you post to a REST API?

To send data to the REST API server, you must make an HTTP POST request and include the POST data in the request's body. You also need to provide the Content-Type: application/json and Content-Length request headers. Below is an example of a REST API POST request to a ReqBin REST API endpoint.

Can you put an array in JSON?

JSON array can store string , number , boolean , object or other array inside JSON array. In JSON array, values must be separated by comma. Arrays in JSON are almost the same as arrays in JavaScript.


2 Answers

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.

like image 190
Adam Liechty Avatar answered Oct 14 '22 13:10

Adam Liechty


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
      },
      ...
    ]
    
like image 21
Tregoreg Avatar answered Oct 14 '22 13:10

Tregoreg