Postman collection doesn't run properly

Hello

I have written a request in Postman that runs fine manually when I run it as well as when I run the schedule manually. However when it runs at the scheduled time, it does not work correctly and even the logs are confusing. I have a delay in my test script that isn’t being honored as well.

In the body, I send in the id of my NetSuite saved search that I am querying and in the pre-request script it is authenticating against NetSuite. Here is the pre-request script logic:

const cyptojs = require('crypto-js');

let tokenClientIDStr = 'prod_ns_token_client_id';
let tokenClientSecretStr = 'prod_ns_token_client_secret';
let tokenIDStr = 'PROD_NS_TOKEN_ID';
let tokenSecretStr = 'PROD_NS_TOKEN_SECRET';
let acctIDStr = 'PROD_NS_ACCOUNT_ID';
let ns_acct_url_id = "7936739";
let custom_search_script_id = "1001";
let custom_search_col_script_id = "1002";

pm.environment.set("ns_acct_url_id", ns_acct_url_id);
pm.environment.set("custom_search_script_id", custom_search_script_id);
pm.environment.set("custom_search_col_script_id", custom_search_col_script_id);

const oauth_consumer_key = pm.environment.get(tokenClientIDStr);  
const oauth_consumer_secret = pm.environment.get(tokenClientSecretStr);
const oauth_token_id = pm.environment.get(tokenIDStr);
const oauth_token_secret = pm.environment.get(tokenSecretStr);
const oauth_account_id = pm.environment.get(acctIDStr); 

const oauth_signing_key = `${encodeURIComponent(oauth_consumer_secret)}&${encodeURIComponent(oauth_token_secret)}`;

const random_source = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let oauth_nonce = '';
for (var i = 0; i < 32; i++) {
    oauth_nonce += random_source.charAt(Math.floor(Math.random() * random_source.length));
}
const oauth_nonce_array = cyptojs.enc.Utf8.parse(oauth_nonce);
const oauth_nonce_final = encodeURIComponent(cyptojs.enc.Base64.stringify(oauth_nonce_array));

const oauth_parameter_string_object = {};

oauth_parameter_string_object.oauth_consumer_key = oauth_consumer_key;
oauth_parameter_string_object.oauth_token = oauth_token_id;

oauth_parameter_string_object.oauth_nonce = oauth_nonce_final;

oauth_parameter_string_object.oauth_timestamp = Math.round((new Date()).getTime() / 1000);

oauth_parameter_string_object.oauth_signature_method = 'HMAC-SHA256';

oauth_parameter_string_object.oauth_version = '1.0';

const oauth_authorization_header_object = {};
for (var key in oauth_parameter_string_object) {
    oauth_authorization_header_object[key] = oauth_parameter_string_object[key];
}

oauth_authorization_header_object.realm = oauth_account_id;

const url_query_string = pm.request.url.getQueryString({  // Postman method to get query string
    ignoreDisabled: true
});

let url_query_string_array = [];

if (url_query_string != ""){
    url_query_string_array = url_query_string.split('&');
}

let url_query_string_object = {};
if (url_query_string !== "") {
    url_query_string_object = JSON.parse(`{"${url_query_string.replace(/&/g, '","').replace(/=/g,'":"')}"}`, function(key, value) {return key === "" ? value : encodeURIComponent(value)});
}

// parse request.params
for (var key in url_query_string_object) {;
    if(url_query_string_object[key] == "%7B%7Bcustom_search_script_id%7D%7D") {
        url_query_string_object[key] = custom_search_script_id;
    } else if (url_query_string_object[key] == "%7B%7Bcustom_search_col_script_id%7D%7D") {
        url_query_string_object[key] = custom_search_col_script_id;
    }
    oauth_parameter_string_object[key] = url_query_string_object[key];
    
}

// sort object by key
const oauth_parameter_string_object_ordered = {};
Object.keys(oauth_parameter_string_object).sort().forEach(function(key) {
    oauth_parameter_string_object_ordered[key] = oauth_parameter_string_object[key];
});

// convert object into array
const oauth_parameter_string_array = [];
for (var key in oauth_parameter_string_object_ordered) {
    oauth_parameter_string_array.push(`${key}=${oauth_parameter_string_object_ordered[key]}`);
}

// generate parameter string
const oauth_parameter_string = oauth_parameter_string_array.join('&');

let base_host = pm.request.url.getOAuth1BaseUrl();
let regexp = /{{(.*?)}}/g;
while (result = regexp.exec(base_host)) {
    let value = pm.environment.get(result[1]);
    base_host = base_host.replace(new RegExp(`{{${result[1]}}}`, 'g'), value);
}

const oauth_base_string = `${pm.request.method}&${encodeURIComponent(base_host)}&${encodeURIComponent(oauth_parameter_string)}`;
let oauth_signature = cyptojs.HmacSHA256(oauth_base_string, oauth_signing_key).toString(cyptojs.enc.Base64);
oauth_authorization_header_object.oauth_signature = encodeURIComponent(oauth_signature);

// convert object into array (for Authorization header string)
const oauth_authorization_header_array = [];
for (var key in oauth_authorization_header_object) {
    oauth_authorization_header_array.push(`${key}="${oauth_authorization_header_object[key]}"`);
}

const oauth_authorization_header = oauth_authorization_header_array.join(', ');

// generate Authorization header, FINALLY!
pm.request.headers.add({
    key: 'Authorization',
    value: 'OAuth ' + oauth_authorization_header
});

// Escape URI parameters using encodeURIComponent => RFC3986
// This is encoding the query string params in the request.
if (url_query_string_array.length !== 0) {
    let request_parameter_array = [];
    for (var key in url_query_string_object) {
        request_parameter_array.push(key + '=' + url_query_string_object[key]);
    }
    const request_parameter_string = request_parameter_array.join('&');

    pm.request.url = pm.request.url.getOAuth1BaseUrl() + "?" + request_parameter_string;
}

Here is the code from the test script:

// Define the delay between each request (in milliseconds)
var delayBetweenRequests = 1000; // 1 second delay

// Function to send requests with delays
function sendRequestsWithDelay(requests, delay) {
    var index = 0;

    function sendNextRequest() {
        if (index < requests.length) {
            var request = requests[index];
            index++;

            pm.sendRequest(request, function (err, response) {
                if (err) {
                    console.error('Error:', err);
                } else {
                    console.log('Response:', response.json());
                }

                // Call sendNextRequest after the delay
                setTimeout(sendNextRequest, delay);
            });
        }
    }

    // Start sending requests
    sendNextRequest();
}

var accessToken = pm.environment.get("zoho_access_token");
console.log(accessToken);
var jsonData = pm.response.json();
var results = jsonData.results;
if (results) {
    let count = 1;
    if(accessToken !== null)
    {
        function sendRequestWithDelay(index) {
            // if (index < results.length) {
            if (index < results.length && count <= 50) {
                let escrow_obj = results[index];
                let values = escrow_obj.values;
                let sumAmount = values['SUM(amount)'];
                let truckVIN = values['GROUP(custcol1)'];
                const moment = require('moment');
                const today = encodeURIComponent(moment().format("YYYY-MM-DD"));

                if (truckVIN !== null) {
                    var requestGetTruck = {
                        url: 'https://www.zohoapis.com/crm/v6/Trucks/search?criteria=((Name:equals:' + truckVIN + ')and(Last_Update_Escrow:less_than:' + today + '))',
                        method: 'GET',
                        header: {
                            'Content-Type': 'application/json',
                            'Authorization': 'Bearer ' + accessToken,
                        }
                    };

                    setTimeout(() => {
                        pm.sendRequest(requestGetTruck, function(err, truckResponse) {
                            if (err) {
                                console.error('Error:', err);
                                return;
                            }
                            if (truckResponse.code === 204) {
                                console.log('204 No Content Received');
                            } else if (truckResponse.code === 200) {
                                var parsedTruck = truckResponse.json();
                                console.log('Response:', truckResponse.json());
                                // if (parsedTruck !== null || parsedTruck != '') {
                                    var truckData = parsedTruck.data;
                                    console.log(truckData);
                                    var truckID = truckData[0].id;
                                    console.log(truckID);
                                    if (truckID !== null) {
                                        pm.sendRequest({
                                            url: 'https://www.zohoapis.com/crm/v6/Trucks/' + truckID,
                                            method: 'PUT',
                                            header: {
                                                'Content-Type': 'application/json',
                                                'Authorization': 'Bearer ' + accessToken
                                            },
                                            body: {
                                                mode: 'raw',
                                                raw: JSON.stringify({
                                                    "data": [{
                                                        "Escrow": sumAmount,
                                                        "Last_Update_Escrow": today
                                                    }]
                                                })
                                            }
                                        }, function(err, updateTruckResponse) {
                                            if (err) {
                                                console.error('Error:', err);
                                                return;
                                            }
                                            console.log('Response:', updateTruckResponse.json());
                                        });
                                    }
                                // }
                            }
                            sendRequestWithDelay(index + 1); // Call the next request
                        });
                    }, delayBetweenRequests);
                }
            }
            count = count + 1;
        }

        // Start sending requests
        sendRequestWithDelay(0);
    }
}

1 Like

First of all, thank you for your post. Based on my apprehension you performed manual runs through the runner. You are confronted to issues whilst running the same collection through the monitor. There is a difference between the API response validation which involves the response time between the monitor and the runner. You may not appropriately visualize the results on the monitor dashboard. I would like to examine and investigate your collection.

Is there a way to share a public link of your your workspace? Or an export of your collection and your environment ? I will be happy to help.

Sorry for the delay, it will let me share the collection file here

Thanks

I believe collections and environments can’t be shared. May you provide me a link to your public workspace I will be happy to assist.

Hello again

I apologize, I do not believe I can share my environment as this is a business solution and we have security practices in place but I could share the collection. Unfortunately, you would need access tokens to NetSuite and Zoho so I think I will just mark this one closed as I have found that Postman Flows accomplish what I need anyway.

Thank you so much for your reply and have a great day!