How to send multiple requests using axios
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:
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.
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.
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:
You can write your code for performing multiple parallel requests:
In the code we followed some steps:
- Import
storyblokInit
andapiPlugin
from our SDK@storyblok/js
; - Define the set of URL/path as array;
- initializing the SDK via
storyblokInit()
using the token for your space; - Calling the
storyblokApi.get()
method for all the URLs/paths set at point 2 (avoiding using the await) - 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