How to user array variable in chain request

Hi,
I’m trying to run 2 API calls, the first will give me an array of ID’s and I want to use that array in the 2nd request.

For example, here is first response:

“status”: 1,
“offers”: [
{
“id”: 9792,
“offer_id”: “5967372b0624dfa73e8b45a7”,
“advertiser”: “59672fcc0624dfab3e8b4995”,
}
{
“id”: 9331,
“offer_id”: “596fdf32b0624dfa73e8b45a7”,
“advertiser”: “596fsdfq1121412e8b4995”,
}
{
“id”: 9112,
“offer_id”: “5535410624dfa73e8b45a7”,
“advertiser”: “r12341cc0624dfab3e8b4995”,
}

I want to save all the ID’s of the offers in an array and use it to run the 2nd API call for each ID in the array
2nd api call: some-domain.com/offer/<>?api-key=1112222

Would appreciate your assistance.

I’ve never done this before, so off the top of my head here’s how I quickly performed the action you wanted:

In the example I’m calling one GET request that just returns user details.
The example URL is:

http://localhost:3000/users/{{userId}}

And here’s an example response:
image

Before we begin, I have 3 environment variables:
“userIds” which has an array of User IDs.
[1, 2, 3, 4, 5, 6]

“counter” which will be a number. This will be set to 0 in a previous request.

Finally, we have a “userId” which is what’s used in the URL. We’ll have some logic in place to pull the correct userId from our “userIds” array.

Down To The Nitty Gritty!!:

In the Pre-Request Script tab I’m taking the current value of our “counter” environment variable.

I’m also performing a JSON Parse on the “userIds” array as Postman saves as env variables as strings.

So! Our “userId” variable will be set to the User ID in our “userIds” array based on the current value of “counter” (I hope that made sense…)

There are lots of comments in the code snippet shown.

In our Tests Tab:

Again, I’m performing a JSON Parse on our “userIds” array.
And I’m taking the current value of our counter variable again.
I’m increasing the value of “counter” by 1 with each request.
I have a condition, that checks if “counter” is NOT equal to the length of the array (minus 1)
If it’s not, I’m using postman.setNextRequest() to hit the same request again (But remember, our counter variable is now greater than before)

You can probably tell this is pretty rushed as I’m at my place of work xD

Good luck! Hope this makes sense.

I’m sure there are MUCH better/cleaner ways of doing this.

Thanks a lot Pfarrell, very helpful !

1 Like

What if the ids are hashes instead.