How to pass array as a parameter

Hi Guys,

I have created a global variable for site_id like this :

but when i request the get in postman i only get site_id = 1

Hi @amygupta7!

Welcome to the community! :clap:

So naturally, environment variables only support one actual value. However, what you can do is make this value in a json format, and then in a pre request script make that json into a native javascript array and do whatever you please with it.

However, given the way you are trying to use your site ID in the request, you generally cannot pass an array as a URL Parameter. What you are looking to do then is make multiple requests for different site IDs.

Here I would suggest using the pre request script to fire off multiple requests with differing site IDs, combine those values then into one variable as a response, including the last request.

Or, you can use collection runner to run multiple requests with different site IDs, albeit they won’t be combined.

I am making assumptions on what you can do, as generally thats how REST services operate. Given that I don’t know anything about your web service, there may be other ways to achieve what you are looking to do.

Hope this help!

Hi odanyl,
Thanks so much for your reply.

In the pre request script do I have to create the array of the site_id?

Are there any help docs for me to review to achieve this please ?

@amygupta7 You’re welcome!

So yes, you would create the array of site_ids in your pre-request script. Or, if you already know these site ids ahead of time, you can place them in an environment variable in json format.

Then you can pull that variable out in your request script and iterate over it, and make a request for each site id.

Example:

(site_ids in environment variables -> [1, 2, 3,])

var site_ids = pm.environment.get("site_ids");

var rootUrl = pm.environment.get("PUBLICAPI_ROOT_URL")

site_ids.forEach({ site_id =>

pm.sendRequest({
    url: rootUrl + "/sites/" + site_id + "/readings/summary?start_date=2020-06-22&end_date=2020-06-24,
    method: "GET",
    header: {
      'Content-Type': 'application/json'  
    }
}, function (err, response) {
    
// Parse Response
var readings = response.json["readings"];

console.log(readings)
    
});

}

Something like this should work, though there may be some syntax errors above. In this case, it will output to console each time you make a request for a different site ID. Now you can add some code so that each time you make a request, you append the results to an array of site_id response to get all your data in one place, but that of course depends on what your end goal is.

Here you can learn more about pre-request scripts:

https://learning.postman.com/docs/postman/scripts/intro-to-scripts/