I am working on some test scripts and data cleanup scripts using postman, and was wondering if it were possible to run a request on an array result produced in a previous step.
For example, I have an API that returns tasks as a JSON like so:
[
{
"active": true,
"_id": "5b2101244651a04a4907b094",
"name": "Test Task",
"updatedAt": "2018-06-13T11:33:56.911Z",
"createdAt": "2018-06-13T11:33:56.911Z"
},
{
"active": true,
"_id": "5b2101244651a04a4907b067",
"name": "Test Task 2",
"updatedAt": "2018-06-13T11:33:56.911Z",
"createdAt": "2018-06-13T11:33:56.911Z"
}
]
So in the Tests scripts I run this to collect an array of the IDs:
var jsonData = JSON.parse(responseBody)
postman.setEnvironmentVariable('task_id_list', jsonData.map((i) => i._id))
The next request is to delete a task, but the API only deletes one at a time. I am trying to do something like:
http://localhost:3000/api/v1/tasks/{{task_id_list}}
I was hoping that Postman would see that task_id_list
was an array and simple "work", but that doesn't seem to be the case. Is it possible to have a step run multiple times based on an array input?
Solution from this article
Get array of ID's in test script of first request (I prefer to store it in JSON to avoid bugs):
let JsonData = pm.response.json();
let iDs = JsonData.map((i) => i._id)));
pm.environment.set("IdArray", JSON.stringify(iDs);
//and now check, if there was no objects returned, stop runner
if(iDs.length === 0)
{
postman.setNextRequest(null);//next request will not be sent
}
else
{
pm.environment.set("count", 0);
}
In pre-request script of 2 request:
var count = +pm.environment.get("count");
var iDs = JSON.parse(pm.environment.get("IdArray"));
pm.variables.set("task_id_list", iDs[count]); //like one-request environment variable
count = count + 1; //next iteration
if(count < iDs.length)
{
postman.setNextRequest("NAME OF THIS REQUEST");
}
else
{
postman.setNextRequest(null); // or next request name
}
pm.environment.set("count", count)
So you should understand my idea.