How to create a collection of GET requests with nested loops and download the data from the nested loop

Hello,

I am fairly new to Postman and need to create a collection of GET requests that:

  1. Gets a list of Buildings
  2. Loops through the array of Buildings and for each Building, finds the Floors
  3. Loops through the array of Floors and for each Floor, finds the Spaces on that Floor
  4. Loops through the array of Spaces and for each Space, gets different attributes such as Area, Created Date, Interior/Exterior, Occupant, Entry Time In, Entry Time Out, etc for a date range
  5. Download all these Space attributes data and upload them to a SQL Server DB.

My GET request for the list of Buildings works ok and I have them in an array.

When I loop through the Buildings array to find the Floors, I am unable to stop the processing once all the values of the array are done.

Also, in my GET request for finding Spaces, the Building ID from the very first GET request is lost. So no other processing happens.

For some reason, the Postman.setNextRequest function fails.

Any help/advise would be very appreciated!

Thanks much!!
AG

How to Loop Through Nested Arrays in Postman Collections

1. Use Collection/Environment Variables to Persist Data

  • Store your arrays (buildings, floors, etc.) in a collection/environment variable after each API call.
  • Store the current index as a variable (e.g., buildingIndex, floorIndex, spaceIndex).

2. Use postman.setNextRequest() for Looping

  • In your test script, use logic to check if more items exist in the array. If yes, call postman.setNextRequest('Your Next Request Name'); if no, end or move to the next loop.
  • To stop looping, use postman.setNextRequest(null);

Your logic appears correct and broken down into the five steps.

For step 5, as you don’t have access to the local file system I would recommend that you interface your SQL DB with an API so its just another API request.

You haven’t said where this is failing or what code you have so far!

Can you please share what you have so far?

Where this is going to get complex is with the IF statements to control the loops.

setNextRequest() just sets the next request that will run after the current request (and all code in the pre and post reponse scripts). So you can’t just loop back to step 2 from step 4.

You are probably going to have to mix some sendRequests() into the mix to get around that problem.

Requests 2, 3, and 4 should be singular requests that loop on “themselves only” with an sendRequest() in the post response script to get the details for the next loop.

1 Like