Hi @awest1. I think I can help.
Since this is partially a Javascript question, I’ll recommend StackOverflow as a great resource. Here’s a question on iterating through arrays, and it has some very thorough answers: Loop (for each) over an array in JavaScript - Stack Overflow
For your use-case, it sounds like you need to send multiple requests with a {{pieceId}}
in each. Is that right?
If that’s the case, you can use Javascript to first loop through your response data, and set a global (or other scope of) variable for each piece.id.
Test script:
var responseJson = pm.response.json();
var data = responseJson[0].items[0].pieces; // the array we're iterating through
for(var i = 0; i < data.length-1; i++) // loop through the array
{
var pieceValue = data[i].id; // the specific value were setting as a global variable
pm.globals.set('piece'+i,pieceValue); // use i to increment the name of the global variable we're setting
}
Then, you can use postman.setNextRequest() to loop the request that’s sending each value, until all values have been sent.
Pre-request script:
// check to see if there is a counter run-scoped variable, and if there isn't create one with value=0.
// this is for iterating through the global variables stored, and stopping when there's none left.
if(!pm.variables.has('counter')){
pm.variables.set('counter',0);
}
// get the current value of the run-scoped variable "counter"
var counter = pm.variables.get('counter');
// if there is a variable called (e.g.) pieceId0, get it's value and set a run-scoped variable
if(pm.globals.has("pieceId" + counter)){
var pieceIdValue = pm.globals.get("pieceId" + counter)
pm.variables.set("pieceIdDynamic",pieceIdValue)
}
// increment the counter variable
counter++;
// store the current value of the Sandbox variable counter, in the run-scoped variable "counter"
// this is so that the counter value persists between loops of the POST request
pm.variables.set('counter',counter);
// if there is another global variable to send, set the next request as this same request (loop it again)
if(pm.globals.has("pieceId"+counter)){
postman.setNextRequest("POST Array Data")
}
Finally, you’ll just need a dynamic variable {{pieceIdDynamic}}
in the request sending the IDs. When you run this Collection via the Collection Runner, or a monitor, it will grab all needed data and send it automatically with just 2 requests!
I put together a working example of this approach. Check out the following docs page, and click Run in Postman to get a copy.
Hope that helps!
Also, here’s some docs from the Learning Center that may also be helpful:
https://learning.getpostman.com/docs/postman/scripts/branching-and-looping/
https://learning.getpostman.com/docs/postman/environments-and-globals/variables/