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?
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);
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.
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.
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.
Basically, the answer I was looking for was:
Content-Type: application/x-www-form-urlencoded
which is standard in web; instead, Content-Type: application/json
should be used,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
},
...
]
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