Retry a failing request


in our test environment, unfortunately quite some requests are failing from time to time, due to timeouts, environment not being available, you-name-it, so I want to give that requests a retry, especially when running the collections in Jenkins via newman.

So I came up with a bit of code, that repeats waits for a certain amount of time, before it does a retry of the request. The number of retries can also be set.

var expectedHttpStatus = 200;
var maxNumberOfTries = 3;
var sleepBetweenTries = 5000;

if (!pm.environment.get("collection_tries")) {
    pm.environment.set("collection_tries", 1);

if ((pm.response.code != expectedHttpStatus) && (pm.environment.get("collection_tries") < maxNumberOfTries)) {
     var tries = parseInt(pm.environment.get("collection_tries"), 10);
     pm.environment.set("collection_tries", tries + 1);
     setTimeout(function() {}, sleepBetweenTries);
 } else {

     pm.test("Status code is " + expectedHttpStatus, function () {

     // more tests here...

Hope it might be of use for someone!




I guess this could be put inside the collection window too? So it’s applicable for all requests in the collection (assuming you’re not doing any negative testing)

I do something kinda similar to test an endpoint that’s using ElasticSearch.
So I create an entry (In my case it’s a customer return in the DB) I then try to use our “search” endpoint to confirm the customer return can be searched, but you have to wait 5-10 seconds for the entry to exist in Elastic, so two solutions:

  1. Hardcode a wait for 10 seconds or so
  2. Keep hitting the search request x times until the entry is shown, if the entry doesn’t appear after x times then consider the test a failure.

I obviously prefer the second solution due to obvious reasons :stuck_out_tongue:

@chrissbaumann This is a good example to publish as a template in Postman!