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

With over 19.5 million weekly downloads, Axios has become a go-to JavaScript library for making HTTP requests. Its versatility and ease of use make it a popular choice among developers. In this article, we’ll explore the benefits of using Axios.create to create custom instances with tailored configurations, allowing you to reuse settings across multiple 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:

“`javascript
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:

javascript
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:

javascript
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:

javascript
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();
“`

Conclusion

In this article, we’ve explored the benefits of using Axios.create to create custom instances with tailored configurations. By doing so, we can reuse settings across multiple API calls, making our code more efficient and scalable. Whether you’re working with multiple APIs or services, Axios.create is an ultra-useful tool that can help you streamline your HTTP requests.

Leave a Reply

Your email address will not be published. Required fields are marked *