Skip to content
Advertisement

Group results of multiple POST API calls

I use the below script to loop through the input (skipping first one) to post some data to my API.

Result

Call 2 {"result":{"number":"002"}}
Call 3 {"result":{"number":"003"}}

How can I capture the combined response of both calls into a variable I can use later on in my script?

something like var allNum = res.result.number[0]?
This is what I want -> Var allTens = "002, 003"

Script

  //input
    var tens = "abc, def, ghi"
    console.log(tens);
    //Break list
    var tenlist = tens.split(',').map(string => string.trim());
    console.log(tenants);
    
    //Start Data loop through tenants skip first value
    var tenants = tenlist.slice(1);
    tenants.forEach(tenant => {
    var data = {};
    var options = {
        'endpoint': 'site',
        'path': '/api/v1/table/record',
        'method': 'POST',
        "headers": {
            "Authorization": "Basic xxxxxxx
            "Content-Type": "application/json"
        }}
      sendData(data, options);
    });
    function sendData(data, options) {
        var req = http.request(options, function(res) {
            console.log('STATUS: ' + res.statusCode);
            console.log('HEADERS: ' + JSON.stringify(res.headers));
        });
       req.write(data);
    
    }

Advertisement

Answer

You can declare a variable outside of the .forEach Call that could be used within that “scope”. This variable can just be an array that you append the results to:

var tens = "abc, def, ghi"
console.log(tens);
//Break list
var tenlist = tens.split(',').map(string => string.trim());
console.log(tenants);

//Start Data loop through tenants skip first value
var tenants = tenlist.slice(1);
var newArray = [];
tenants.forEach(tenant => {
var data = {};
var options = {
    'endpoint': 'site',
    'path': '/api/v1/table/record',
    'method': 'POST',
    "headers": {
        "Authorization": "Basic xxxxxxx",
        "Content-Type": "application/json"
    }}
  sendData(data, options);
});
function sendData(data, options) {
    var req = http.request(options, function(res) {
        console.log('STATUS: ' + res.statusCode);
        console.log('HEADERS: ' + JSON.stringify(res.headers));
        newArray.push(res); //This'll certainly need changing - but this adds to the array
    });
   req.write(data);

}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement