DEV Community

Abhinav Sachdeva
Abhinav Sachdeva

Posted on • Edited on

2

API Calls with retries

Have you run into a situation when you needed to call a buggy API that responds with an error ever so often?
What's the solution if you have no control over that API?

Retries to the rescue!

As it happens...

  1. Our fetchDataWithRetries function takes in the maxReties (uses 3 as a default value)
  2. When called, this function returns a function and we make use of closure to capture the value of tries and maxTries
  3. The returned function - apicall - takes in the URL to be called.
    1. If the response is a success - return it as is
    2. If there's an error increment the tries, check for max retry limit and recursively call itself

    const fetch = require('node-fetch');

    function fetchDataWithRetries(maxTries) {
        maxTries = parseInt(maxTries);
        if(!maxTries) maxTries =  3;
        let tries =  0;
            return function apicall(url) {
                if (!url) return Promise.reject("URL required")
                console.log("APICALL " + (tries + 1));
                return fetch(url)
                    .then(function (res) {
                        console.log("fetch success");
                        return res.json();
                    })
                    .catch(e => {
                        console.log("Fetch Error")
                        if (++tries < maxTries)
                            return apicall(url);
                        return Promise.reject(e)
                    });
            }
   }

 const  retyCount = 2, APIURL = 'https://jsonplaceholder.typicode.com/users/1';

fetchDataWithRetries(retyCount)(APIURL)
    .then(data => console.log(data))
    .catch(err => console.log(err));
Enter fullscreen mode Exit fullscreen mode

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (2)

Collapse
 
leandroandrade profile image
Leandro Andrade

Great simple explanation, just add "url" when run "apicall" in catch fetch.

Collapse
 
abhinavsachdeva profile image
Abhinav Sachdeva

Thanks for the read. Updated.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay