Unlock the Power of Axios: Creating Custom Instances for Efficient API Calls

The Benefits of Axios.create

Axios.create is a factory function that generates new instances of Axios with custom configurations. This feature enables you to create multiple instances of Axios, each with its own settings, to interact with different APIs or services. By doing so, you can reuse the configuration for all calls made using the same instance, making your code more efficient and scalable.

Setting Up a Demo Project

Before we dive into the code, make sure you have the following prerequisites:

  • Working knowledge of JavaScript
  • Node.js (preferably the latest LTS version) installed on your machine
  • Working knowledge of npm functions

To set up a new project, run the following command to create a package.json file:

npm init -y

Next, install Axios using npm:

npm install axios

Creating a Custom Axios Instance

To demonstrate the power of Axios.create, we’ll build a simple GitHub API client that calls multiple endpoints. First, we’ll create a custom Axios instance with a base URL and timeout configuration:

const axios = require('axios');

const githubInstance = axios.create({
  baseURL: 'https://api.github.com/',
  timeout: 1000,
  headers: {
    Accept: 'application/vnd.github.v3+json'
  }
});

Using the Custom Instance

Now, let’s use the custom instance to call the GitHub API. We’ll create an async function to retrieve the list of users with the most followers:

async function getMostFollowedUsers() {
  const response = await githubInstance.get('search/users', {
    params: {
      q: 'followers:>35000',
      per_page: 10
    }
  });
  return response.data.items;
}

Overriding Configurations

What if we need to override the default timeout for a specific API call? Axios.create allows us to do just that:

async function getCounts(username) {
  const response = await githubInstance.get(`users/${username}`, {
    timeout: 1500
  });
  return response.data;
}

Putting it All Together

Let’s create an async function to retrieve the list of users with the most followers, along with their public repository count and follower count:

async function main() {
  try {
    const users = await getMostFollowedUsers();
    const usernames = users.map(user => user.login);
    const results = await Promise.all(usernames.map(getCounts));
    console.table(results);
    results.forEach(result => {
      console.log(`Username: ${result.login}, Public Repos: ${result.public_repos}, Followers: ${result.followers}`);
    });
  } catch (error) {
    console.error(error);
  }
}

main();

Leave a Reply