Storyblok Raises $80M Series C - Read News

What’s the True Total Price of Enterprise CMS? Find out here.

Skip to main content

How to send multiple requests using axios

Try Storyblok

Storyblok is the first headless CMS that works for developers & marketers alike.

In case you need to retrieve information from multiple data sources or multiple API endpoints, you can use Axios or our Javascript SDK (https://github.com/storyblok/storyblok-js) to retrieve make HTTP calls simultaneously, in parallel.

Performing multiple HTTP requests with Axios

In this article, we will see how you can achieve concurrent execution of HTTP calls by taking advantage of the Promise feature. First, make sure you have installed Axios:

        
      npm install axios
    

Now we installed Axios, let's start with a small task and send one request using Axios. In the example, we will set one URL for accessing the Content Delivery API (version 2) provided by Storyblok.

        
      import axios from "axios";

// Set the URL to access
let token = "wANpEQEsMYGOwLxwXQ76Ggtt";
let version = "published";
let url =
  `https://api.storyblok.com/v2/cdn/stories/health?` +
  `version=${version}&token=${token}`;
/*
| Perform the HTTP get request via Axios
| It returns a Promise immediately,
| not the response
*/
const request = axios.get(url);
/*
| For waiting the Promise is fulfilled
| with the Response use the then() method.
| If the HTTP request received errors
| use catch() method
*/
request
  .then((response) => {
    console.info(response.data.story);
  })
  .catch((error) => {
    console.err(error);
  });
    

First, we import Axios and define the API/URL we want to load from. Then, we can call the get() method. Because the get() method is asynchronous, a Promise object is returned. With the Promise object, we can set the callback for managing the fulfilled response via the then() method. To manage also the error, we can use the catch() method.

Since axios returns a Promise, we can go for multiple requests using Axios.all().

Then, we define the different URLs we want to access.

        
      import axios from "axios";

// Set the URLs to access
let urls = [
  "https://api.storyblok.com/v2/cdn/stories/health?version=published&token=wANpEQEsMYGOwLxwXQ76Ggtt",
  "https://api.storyblok.com/v2/cdn/datasources/?token=wANpEQEsMYGOwLxwXQ76Ggtt",
  "https://api.storyblok.com/v2/cdn/stories/vue?version=published&token=wANpEQEsMYGOwLxwXQ76Ggtt",
];
/*
| Perform the HTTP get request via Axios
| It returns a Promise immediately,
| not the response
*/
const requests = urls.map((url) => axios.get(url));
/*
| For waiting the Promise is fulfilled
| with the Response, use the then() method.
| If the HTTP request received errors
| use catch() method
*/
axios.all(requests).then((responses) => {
  responses.forEach((resp) => {
    let msg = {
      server: resp.headers.server,
      status: resp.status,
      fields: Object.keys(resp.data).toString(),
    };
    console.info(resp.config.url);
    console.table(msg);
  });
});
    

We defined a list of URLs as an array. Using map() method, we call multiple axios.get() for each URL in the array. Then, in the requests array, we have the list of the promises, one Promise object for each request sent. Then with axios.all() we obtain all the fullfilled responses from all the requests. All the requests are sent in parallel.

Performing multiple HTTP requests using the Storyblok Javascript SDK

Our Javascript SDK depends on the Storyblok universal JS client version 5, which uses the new fetch() method instead of Axios. But don't worry, our SDK can also return a Promise, so you can achieve the same level of concurrency in the same way, achievable through Axios. So you can use the same approach shown above, setting up the promises for all the requests. Once you have installed the Storyblok Javascript SDK:

        
      npm install @storyblok/js
    

You can write your code for performing multiple parallel requests:

        
      import { storyblokInit, apiPlugin } from "@storyblok/js";

// Set the URL paths to access
let paths = ["cdn/stories/health", "cdn/datasources", "cdn/stories/vue"];
/*
| Initialize the StoryblokClient once
*/
const { storyblokApi } = storyblokInit({
    accessToken: "wANpEQEsMYGOwLxwXQ76Ggtt",
    use: [apiPlugin],
});

/*
| Perform the HTTP get request via get() method
| provided by storyblokApi.
| It returns a Promise immediately,
| not the response
*/
const requests = paths.map((path) =>
    storyblokApi.get(path, { version: "published" })
);
/*
| For waiting the Promise is fulfilled
| with the Response, you can use Promise.all and
| use the then() method.
| If the HTTP request received errors
| use catch() method
*/
Promise.all(requests).then((responses) => {
    responses.forEach((resp) => {
        console.log(resp.data);
    });
});
    

In the code we followed some steps:

  1. Import storyblokInit and apiPlugin from our SDK @storyblok/js;
  2. Define the set of URL/path as array;
  3. initializing the SDK via storyblokInit() using the token for your space;
  4. Calling the storyblokApi.get() method for all the URLs/paths set at point 2 (avoiding using the await)
  5. Manage all the promises returned by point 4 via Promise.all().then().

Executing multiple HTTP calls concurrently can reduce the total response time, improving the performance of the execution of the logic you implement.

Curious to keep learning?

Check out Storyblok, bringing you the latest tech solutions to stay on top of your game

Authors

Dominik Angerer

Dominik Angerer

A web performance specialist and perfectionist. After working for big agencies as a full stack developer he founded Storyblok. He is also an active contributor to the open source community and one of the organizers of Scriptconf and Stahlstadt.js.

Roberto Butti

Roberto Butti

Roberto is a Developer Relations Engineer at Storyblok who loves supporting teams for building websites focused on the code's performance and code quality. His favorite technologies include Laravel, PHP, Vue, Svelte and ... Storyblok. He loves exploring and designing composable architectures.