Retrying API with HTTP status code 202

There may be a case when you want the app to keep sending the same request until the result is ready. For example, you may want the API to keep returning 202 status code until the data is ready, and then return a 200 with all the data.

Below is the approach we suggest to implement this kind of logic:

  1. Create a new action of the HTTP Request type (called here apiCall):

    1. Specify the method and URL.

    2. Select the Transform result toggle and in the Modify the result field add return {{res}};. This will return the status of the API request as, by default, the HTTP step returns the body of the response.

  1. Create another action of the JavaScript Code type (called here callApiWithRetries) and specify the following code:

async function makeApiCallWithRetry(maxRetries = 10, delay = 2000) {
  let retries = 0;

  while (retries < maxRetries) {
    const response = await {{actions.apiCall.trigger()}}

    // If the response is 200, return the data
    if (response.status === 200) {
      return response.body;
    }

    // If the response is 202, retry after a delay
    if (response.status === 202) {
      retries++;
      await new Promise(res => setTimeout(res, delay));
    } else {
      throw new Error(`Unexpected status code: ${response.status}`);
    }
  }
}
return await makeApiCallWithRetry();

Here, the action is called programmatically with actions.apiCall.trigger(), which allows you to easier control retry logic. But you can also make this retry action generic and execute it providing actionName via params. To do so, you simply need to change the code to actions[params.actionName].trigger():

actions.apiCall.trigger() -> actions[params.actionName].trigger()

Last updated

Was this helpful?