Reputation: 1802
Let's say I have an API endpoint /bar
that returns:
{
"fooIds": [1,2,3]
}
and a /foo/<id>
endpoint that i would like to call with those ids.
Is there way of getting postman to make a call to the /bar
endpoint and subsequent calls to /foo
?
Upvotes: 0
Views: 3102
Reputation: 81
Create yourself a collection in Postman with two requests. The first one for /bar
, second one for /foo/{{id}}
where {{id}}
is a Postman parameter stored in either the globals or environment variables (either place is fine, the example below uses the globals).
Then in the test script of the first request save fooIds to the globals with
pm.globals.set('fooIds', pm.response.json().fooIds.join(','));
In the pre-request of the second request
// fetch the fooIds into an array (leaves it undefined if not found)
const fooIds = pm.globals.has('fooIds') && pm.globals.get('fooIds').split(',');
// if fooIds was found, and has a first element, save it
fooIds && fooIds[0] && pm.globals.set('id',fooIds.shift()); // .shift() removes the first element
// save the updated fooIds back to the globals
pm.globals.set('fooIds', fooIds.join(','));
Note: when fooIds = []
, then fooIds.join(',')
returns "", and setting a global variable to "" deletes it.
and finally in the test script of the second request
pm.globals.has('fooIds') && postman.setNextRequest('nameOfFooRequest')
If you run that in the Postman Collection Runner, that should (hopefully) iterate over the array of id's.
(be sure to save before you run as you might have an infinite loop)
Let me know if you have any issues.
Upvotes: 4