DEV Community

Saulo Dias
Saulo Dias

Posted on

Using Axios more elegantly with Interceptors and Array of URLs

Axios is a popular library for making HTTP requests in JavaScript. It provides a simple and intuitive API for sending requests and handling responses. In this post, we'll explore how to use Axios more elegantly by creating an array of URLs and using interceptors for common headers.

Setting up Access Token and API Endpoints

First, we need to set up our access token and API endpoints. We'll define our access token as a constant, and our endpoints as an object with keys representing each endpoint and values representing the endpoint URL.

const accessToken = "INSERT YOUR ACCESS TOKEN HERE";
const endpoints = {
  basicProfile: "/users/profile",
  skills: "/users/skills",
  positions: "/users/positions",
}
Enter fullscreen mode Exit fullscreen mode

Creating an Instance of Axios

Next, we'll create an instance of Axios with a base URL and common headers. We'll use the create method of the axios object to create this instance. We'll also include our access token in the Authorization header and set the Content-Type and X-Restli-Protocol-Version headers.

const api = axios.create({
  baseURL: "https://api.example.com/v2",
  headers: {
    Authorization: `Bearer ${accessToken}`,
    "Content-Type": "application/json",
    "X-Restli-Protocol-Version": "2.0.0",
  },
});
Enter fullscreen mode Exit fullscreen mode

Using Interceptors to Set Base URL

We'll use an interceptor to set the base URL for all requests. This will allow us to specify only the endpoint name when making requests, rather than the full URL. We'll use the request interceptor to modify the config object and set the url property to the corresponding URL from our endpoints object.

api.interceptors.request.use((config) => {
  config.url = endpoints[config.url];
  return config;
});
Enter fullscreen mode Exit fullscreen mode

Using an Array of URLs to Fetch Data

Finally, we'll use an array of URLs to fetch data from multiple endpoints. We'll use the Promise.all method to send multiple requests at once and wait for all of them to complete. Once the requests are complete, we'll extract the data from each response and use it as needed.

Promise.all([api.get("basicProfile"), api.get("skills"), api.get("positions")])
  .then((responses) => {
    const basicProfile = responses[0].data;
    const skills = responses[1].data.elements;
    const positions = responses[2].data.elements;

    // Use fetched data
  })
  .catch((error) => {
    console.error(error);
  });
Enter fullscreen mode Exit fullscreen mode

In this example, we're fetching data from three endpoints: basicProfile, skills, and positions. We're using an array of URLs to make the requests, and the Promise.all method to wait for all of them to complete. Once the requests are complete, we're extracting the data from each response and using it as needed.

By using an array of URLs and interceptors for common headers, we can make our code more elegant and easier to read. These techniques can also help reduce boilerplate code and improve the maintainability of our codebase.

Top comments (0)