Collection Runner - Skip API call based on condition in script

I have three APIs. API#1, API#2, API#3
API#1 returns names e.g. {{endPoint}}/GetNames
API#2 returns phone number(s) for a particular name e.g. {{endPoint}}/GetPhoneNo/{{name}}
API#3 returns carrier names for a particular phone number e.g. {{endPoint}}/GetCarrier/{{phoneNo}}
I get an array of names from API#1 response body. I store them in an environment variable nameArray in the Tests script of API#1

Tests of API#1

pm.variables.set("nameArray", pm.response.json().names);
pm.variables.set("phoneNoArray", []);

I use the nameArray in Pre-request Script of API#2 to call API#2 on a per name basis. Then in the Tests Script of API#2, I populate phoneNoArray from the response body of API#2.

Pre-request Script of API#2

if(nameArray.length){
    pm.variables.set("name", nameArray.shift());
    postman.setNextRequest(pm.info.requestName);
}

Tests of API#2

pm.variables.get("phoneNoArray").push(pm.response.json().phoneNo);

Now, there could be a scenario where, none of the names have a phone number i.e. phoneNoArray is empty. In this case I don’t want to call API#3 as it would be an invalid call. So I have the following

Pre-request Script of API#3

if(phoneNoArray.length){
    pm.variables.set("phoneNo", phoneNoArray.shift());  
    postman.setNextRequest(pm.info.requestName);
}
else{
    //If there are no phone numbers, do not call API#3
    postman.setNextRequest();
}

This obviously doesn’t work because it would make one call to API#3 as we can’t skip call to API#3 when the checking condition is itself in Pre-request Script of API#3. The check needs to be in API#2. I am not sure how do I put the check in API#2 as it runs in a loop.

Hi @ontherocks

You could move your postman.setNextRequest(); calls into the “tests” tab instead.

The pre-req runs before the call is executed and the tests tab after the call executes. This means that once API 1 is called you would set in the tests tab that the next one to run is API 2. Then when API 2 runs, the tests tab would set API 3 in the conditional statement.

The else would need postman.setNextRequest(null); (notice the null, this is used to end the next request sequence).

This would stop API 3 from being triggered if the array is emtpy.

@w4dd325 I did some further experiments with your suggestion. Now it works. Thanks :ok_hand: