How to loop over array to change input of request?

Hello Community,

I am quite new to Postman and I am trying to solve the following problem:

I am sending requests, that depend on a longitude and a magnitude (2 keys with the belonging values).


I want to make the values variable such that I can read them from two arrays with longitudes and latitudes and iterate over these arrays until all requests for all information of the wanted different locations are sent.

I am not quite sure if and how it is possible. I only found posts regarding running tests in loops.
Maybe someone can help.

Thank you very much in advance.

@mjmag Welcome to the Community :wave:

So here you already have an array with list of values for Latitude and Longitude and you need to read from it? Or those values are getting generated from different requests or you are generating the values for them?

Or you are looking to save the Longitude and Latitude values in an array to use them in the further requests? Can you please details it here.

Thank you very much for that fast answer.
Sorry for not specifying correctly.

I already have two arrays with list of values for Latidudes and the belonging Longitudes, like:

Lats = [1,2,3,4,5]
Longs = [1,2,3,4,5]

At every request I need to fill in one Latitude and one Longitude. Now I want to start the first request with the first value pair and loop over the arrays for further requests and save the information (as seperate JSON files) for each of these requests.

@mjmag Can you try pasting the below in your pre-request script,

pm.environment.set("Latitude", value[Lats]);
pm.environment.set("CountofLats", Number(Lats) + 1);


pm.environment.set("Longitude", value[Longs]);
pm.environment.set("CountofLongs", Number(Longs) + 1);

and try to access the variables Latitude and Latitude in your request.

This looks exactly like what I am looking for… But I get this Error:

is it correct that I am defining the arrays also in the Pre-request Script?

This helps you on the arrays. So it should look like:

var Lats = ["1","2","3","4"];

Oops, sorry for that, I was writing parallel with a coding language that is syntactically “simpler”…

But still with the correct syntax I get the same ReferenceError:

Sorry to be so demanding. I am just lacking of experience and therefore also of creativity to solve it…

No worries @mjmag, we all start somewhere!

The issue with your code is that you are trying to reference a value object that does not exist.

I would approach this slightly different because even if this code worked to get you lat/long values, it wouldn’t loop, it would only run one time.

So let’s start by assuming you have your latitude and longitude arrays stored in environment variables: latitudeArray and longitudeArray.

In your prerequest script, you will want to add something like this:

// Load the latitude and longitude arrays from the environment
const latitudeArray = pm.environment.get('latitudeArray');
const longitudeArray = pm.environment.get('longitudeArray');

// Load the index counter
let index = pm.environment.get('latLongIndex');
if(!index){
  index = 0;
}

// Set the variables for this iteration and increment the counter
pm.environment.set('latitude', latitudeArray[index]);
pm.environment.set('longitude', longitudeArray[index]);
pm.environment.set('latLongIndex', (index+1));

Then in your test scripts, you would add the following code:

const latitudeArray = pm.environment.get('latitudeArray');
const longitudeArray = pm.environment.get('longitudeArray');
const index = pm.environment.get('latlongIndex');

// Check to see if we need to do another loop
if(index < latitudeArray.length && index < longitudeArray.length) {
  // If another loop is required, set the next request to this one. 
  postman.setNextRequest(request.name);
}
else {
  // If another loop is not required, clear out the index variable for next time.
  pm.environment.unset('latLongIndex');
}

Note - you cannot run multiple requests manually. You would have to run this through the collection runner for it to loop through all of your lat/long values.

1 Like

This already helps a lot - thank you very much!

I think we are getting close, but something seems to go wrong with setting the index.

Somehow it tries to read it instead of setting it to zero.

It seems to be a type problem.

I modified the code a bit with an already existing variable called ‘latLongIndex’ in the environment:

// Load the latitude and longitude arrays from the environment

const latitudeArray = pm.environment.get('latitudeArray');

const longitudeArray = pm.environment.get('longitudeArray');

// Load the current index 

const index = Number(pm.environment.get('latLongIndex'));

console.log("The value of the index is "+index)

// Set the variables for this iteration and increment the counter

pm.environment.set('latitude', latitudeArray[index]);

pm.environment.set('longitude', longitudeArray[index]);

pm.environment.set('latLongIndex', (index+1));

console.log(pm.environment.get('latLongIndex'));

Then I get this errror:

I don’t really understand why it is not recognizing an integer as such.

Here a snapshot of my variables for the environment when I start the collection run:

image

Everything stored in a variable is a string so you would need to convert that string to an integer.

For example: parseInt(pm.environment.get('var_name'))

1 Like

Is there any way to parse the Arrays as well?

You can use JSON.parse(myVariable) to parse an array.

1 Like

Guys, thanks a lot… you got me to a point where I have a script, that is doing what I want it to do.

Now I just have one question left, which is less technical (hopefully):
Every request is responding with a JSON file with the wanted information. How can I save these responses during the loop … or… where can I find it?
After the successful run of the Runner I can choose -> Export Results. But this is giving me a report of the run (i.e. running time etc.).

How can I find the actual responses of the API?

If someone is interested here the code that works:

Pre-request:

// Load the latitude and longitude arrays from the environment

const latitudeArray = JSON.parse(pm.environment.get('latitudeArray')); // Parse from string to array

const longitudeArray = JSON.parse(pm.environment.get('longitudeArray'));

// Check array by log.output

console.log(latitudeArray)

// Load the current index 

const index = parseInt(pm.environment.get('latLongIndex')); //Parse from string to Integer

// Some log.outputs to follow what's happening

console.log("The value of the index is " + index);

console.log((index+1)+". entry of array: "+ parseFloat(latitudeArray[index]));

// Set the variables for this iteration and increment the counter

pm.environment.set('latitude', parseFloat(latitudeArray[index]));

pm.environment.set('longitude', parseFloat(longitudeArray[index]));

pm.environment.set('latLongIndex', (index+1));

Test:

const latitudeArray = JSON.parse(pm.environment.get('latitudeArray'));

const longitudeArray = JSON.parse(pm.environment.get('longitudeArray'));

const index = parseInt(pm.environment.get('latLongIndex'));

// Check to see if we need to do another loop

if(index < latitudeArray.length && index < longitudeArray.length) {

  // If another loop is required, set the next request to this one. 

  postman.setNextRequest("RequestName");

}

else {

  // If another loop is not required, set index back to 0 for next time.

pm.environment.set('latLongIndex', 0);

}

What do you want to do with the responses?

I want to export them in a JSON format to visualize them in a different program.

I’ve never tried to do this myself, so I’m not positive if there is a way to do it natively in the app.

Something you can always do is save the responses to an environment variable, then when the collection run is done just copy the value out of postman and use it wherever you need. Something like this:

let responses = pm.environment.get('responses');
if(!responses){
  responses = [];
}
else {
  responses = JSON.stringify(responses);
}

const jsonData = pm.response.json();
responses.push(jsonData);

pm.environment.set('responses', JSON.stringify(responses));

Jep, seems like I have to use “Newman” for this.

My first solution is just saving the JSONs as global variables, but they have to be downloaded and deleted after each run:

// Set global variable with response body

pm.globals.set('response_body'+index, JSON.stringify(pm.response.json()))

Thanks again for the fast and helpful replies!

How about you save all the responses to a variable, then you add a request at the very end of your collection that saves the response data to Google Sheets?

That way you have all the results in the cloud, it’s saved automatically, and it’s easily maintainable?

1 Like

That’s quite a nice idea for a first solution.
I will look at it a little more deeply on Monday and try to implement it.
Thanks a lot and I will keep you informed how it works.

1 Like