Multiple addresses in testscript or json

Hi folks, I’m a newbie in Postman; I’m working on automating more than 100 get requests to different addresses; now, the automation is ok only if I create a single Get request for each address, but I would like to create a single Get request passing an array of addresses as JSON o directly in the script. I tried to do it by passing an array in the script, but I got an error. I don’t found anything about it in the Postman documentation, someone can help me?

This is my code in the Scripts section (post-response):


// Array of addresses to test
const addresses = [
    'http://address1',
    'http://address2',
    'http://address3'
];

// Function to send requests for all addresses
function sendRequests(addresses) {
    addresses.forEach((address, index) => {
        pm.sendRequest(address, function (err, response) {
            // Log the request and response
            console.log(`Request #${index + 1}: ${address}`);
            console.log(`Response Status Code: ${response.status}`);
            console.log(`Response Body: ${response.text()}`);
            
            // You can also add your assertions here
            pm.test(`Request #${index + 1} should return a 200 status code`, function () {
                pm.expect(response.status).to.eql(200);
            });
        });
    });
}

// Call the function to send the requests
sendRequests(addresses);

/** 
pm.test("Status test", function () {
    pm.response.to.have.status(200);
});
*/

As address in the GET request I have the global variable {{urls}}.

When I try to Send the request I have the error: Error: getaddrinfo ENOTFOUND {{urls}}

Error: getaddrinfo ENOTFOUND {{urls}}
Request Headers
User-Agent: PostmanRuntime/7.41.0
Accept: /
Postman-Token: aecda7ac-2054-4611-968b-2d1b6af12852
Host: {{urls}}
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Request Body

The error is not with that code.

Where is this {{urls}} variable being called from?

You can also achieve this by using a straight up request in the GUI.

if (typeof array === 'undefined' || array.length == 0) {
    array = pm.environment.get("addresses") // array of URL's
    pm.environment.unset("url");
}

let currentAddress = array.shift();
pm.environment.set("url", currentAddress); // use this variable in the request

if (array.length > 0) {  
    currentRequest = pm.info.requestName;
    pm.execution.setNextRequest(currentRequest);
} 

This uses a JavaScript method called shift() that is available to arrays. This returns the first element in the array, and also deletes it from the array.

You can use this in conjunction with setNextRequest() to control the loop. (You need to run this through the collection runner as setNextRequest only works with the collection runner).

If you are going to use sendRequest. Define the body and method, and also add some error handling.

let request = {
    url: 'https://postman-echo.com/get?test=' + i,
    method: 'GET',
}
pm.sendRequest(request, (err, res) => {
    if (err) {
        console.log(err);
    } else {
        pm.test(`Request ${i} - status code is 200`, () => {
            pm.expect(res).to.have.status(200);
            let resJson = res.json();
            console.log(resJson.args.test);
        });
    }
});

Thank you very much Mike, but I’m sorry, I don’t understand how work it. I’m searching in postman documentation but I don’t find anything about jason usage as array and/or similar solution

Now I’m working as follow:

  • Create a global variable as json array “urlList”
  • In the pre-request I’ve this code:
// Get the list of URLs from the environment variable
let urlList = JSON.parse(pm.environment.get("urlList")).urls;

// Get the current index from the environment, default to 0
let currentIndex = pm.environment.get("currentIndex") || 0;

// Set the current URL based on the current index
let currentUrl = urlList[currentIndex];

// Set the request URL to the current URL
pm.environment.set("currentUrl", currentUrl);

// Increment the index for the next iteration
currentIndex++;

// Check if we have reached the end of the list
if (currentIndex >= urlList.length) {
    // Reset index to 0 or set a flag to stop the iteration
    currentIndex = 0; // Reset to loop again, or
    // pm.environment.unset("currentIndex"); // Uncomment to stop iteration after one loop
}

// Save the updated index back to the environment
pm.environment.set("currentIndex", currentIndex);

  • in the GET URL request I have the current URL previously declared in the pre-request: {{currentUrl}}
  • when I run the collection I’ve the error: There was an error in evaluating the Pre-request Script:JSONError: “undefined” is not valid JSON
    GET http://{{currenturl}}/

Error: getaddrinfo ENOTFOUND {{currenturl}}

First point is that variables are case sensitive.

You appear to be setting “currentUrl”, but the error is returning {{currenturl}}.

currenturl will be undefined, and will cause that error.

Use the array.shift() method to loop through the Urls, and use console logs to troubleshoot.

if (typeof urlList === 'undefined' || urlList.length == 0) {
    // Get an array of URLs from the environment variable
    let urlList = JSON.parse(pm.environment.get("urlList")).urls;
    console.log(urlList);
    pm.environment.unset("Url");
}

// Get the first URL in the list (and then remove it from the list)
let currentUrl = urlList.shift();
console.log(currentUrl);

// Set the request URL to the current URL
pm.environment.set("Url", currentUrl);
// try to avoid calling the variables the same name.
console.log(pm.environment.get("Url")) // change your URL to {{Url}}

// Check if we have reached the end of the list
if (urlList.length > 0) {
    // if not, keep running the current request
    currentRequest = pm.info.requestName;
    pm.execution.setNextRequest(currentRequest);
}

I don’t understand why it returns the lowercase “currenturl” error, if everywhere I set “currentUrl” like this. Jo tried following your advice but I still get the same error. Thanks a lot

Can you please show a screenshot of your POST request where you set the URL.

Can you also show me what the urlList variable looks like?

Are the URLS prefaced with HTTP or not.

Pre-request:

Post-response:

Global variable as json:

Yes, the URLS are prefaced with http

You have the urlList set as a global variable, not an environment variable.

You can either add it as an environment variable or change the scripts to use pm.variables.get (which will get a variable with the narrowest scope, if it only exists as a global variable, then it should return it).

Pretty sure you don’t need this array available to all collections in your workspace though. (So I would recommend changing it to an environment or collection variable).

You need to include console logs in your scripts to troubleshoot issues like this.

If you did this…

if (typeof urlList === 'undefined' || urlList.length == 0) {
    // Get an array of URLs from the environment variable
    let urlList = JSON.parse(pm.environment.get("urlList")).urls;
    console.log(urlList);
    pm.environment.unset("Url");
}

Then the console log would returned “undefined” which should tell you that you have an issue to investigate.

This would also confirm that the URL is set. Console log the variable just after setting it.

// Set the request URL to the current URL
pm.environment.set("Url", currentUrl);
// try to avoid calling the variables the same name.
console.log(pm.environment.get("Url")) // change your URL to {{Url}}

That would also currently return undefined.

The actual error is telling that you have an undefined variable but doesn’t tell you which line or variable is at fault, which is why you need the console logs in the right places. This is being caused by the JSON.parse line which quite rightly can’t parse the variable as its undefined.

Therefore when you set the currentUrl variable, it will also be undefined.

If you do go down the environment variables route, make sure you have the environment selected when you run the request\collection.

Please note: There is nothing in your pre or post scripts that will cause this to loop.

I can only refer you back to my previous code snippet as a quick way to control the loop which can be done in the pre-request script. You don’t need to add anything to the post response scripts for this to work.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.