If you're working with APIs that require data from multiple sources, you may struggle with fetching data from different endpoints using the Fetch API.
In this guide, we'll take a deep dive into the Fetch API and show you how to fetch data from multiple endpoints easily.
Basic Usage of the Fetch API
The Fetch API is a modern, web-based API that easily fetches resources asynchronously across the network.
To make a basic fetch request, you simply need to pass the URL of the resource you want to fetch to the fetch()
method. The fetch()
method returns a Promise that resolves to the Response object representing the resource you fetched. Here's an example:
js
fetch('https://example.com/api/data')
.then(response => {
console.log(response);
})
.catch(error => {
console.error(error);
});
Fetching Data from Multiple Endpoints
Fetching data from multiple endpoints is a common requirement when working with API. You can gather information from various sources and merge it into a single result set.
Chaining multiple fetch requests
One way to fetch data from multiple endpoints is by chaining multiple fetch requests together. In this approach, you make a fetch request to the first endpoint and then use the response from that request to make another fetch request to the next endpoint.
js
fetch('https://example.com/endpoint1')
.then(response => {
return response.json();
})
.then(data1 => {
return fetch(`https://example.com/endpoint2?data=${data1}`);
})
.then(response => {
return response.json();
})
.then(data2 => {
console.log(data2);
})
.catch(error => {
console.error(error);
});
In this example, we're making a fetch request to https://example.com/endpoint1
and using the response data to construct a URL for the second fetch request to https://example.com/endpoint2
. The response from the second request is then parsed as JSON and logged to the console.
Using Promises to handle multiple fetch requests
Another way to fetch data from multiple endpoints is by using Promises. In this approach, you create an array of Promises representing each fetch request and then use the Promise.all()
method to wait for all the requests to complete before handling the responses. Here's an example:
js
const request1 = fetch('https://example.com/endpoint1').then(response => response.json());
const request2 = fetch('https://example.com/endpoint2').then(response => response.json());
Promise.all([request1, request2])
.then(([data1, data2]) => {
console.log(data1, data2);
})
.catch(error => {
console.error(error);
});
In this example, we're creating two Promises representing the fetch requests to https://example.com/endpoint1
and https://example.com/endpoint2
, respectively. We then pass these Promises to the Promise.all() method waits for both requests to complete before resolving with an array of the response data. Finally, we log the response data to the console.
Usage
Let's use the GeoDB Cities API from Rapid API Hub in this example. You can sign up and subscribe to use this API.
We’ll be using the request chaining method for this example. In this, we fetch data from the first endpoint using a single fetch call, then fetch data from the second endpoint in the then()
block of the first fetch call using another fetch call. The data from each endpoint is then logged to the console.
html
<!DOCTYPE html>
<html>
<head>
<title>Fetch API Example</title>
</head>
<body>
<h1>Fetching Data from Multiple Endpoints</h1>
<script>
// First endpoint to fetch data from
const endpoint1 = 'https://wft-geo-db.p.rapidapi.com/v1/geo/countries';
// Fetch data from first endpoint
fetch(endpoint1, {
headers: {
'x-rapidapi-key': 'your-api-key',
'x-rapidapi-host': 'wft-geo-db.p.rapidapi.com'
}
})
.then(response => response.json())
.then(data1 => {
console.log(data1);
// Second endpoint to fetch data from
const endpoint2 = 'https://wft-geo-db.p.rapidapi.com/v1/geo/cities';
// Fetch data from second endpoint
return fetch(endpoint2, {
headers: {
'x-rapidapi-key': 'your-api-key',
'x-rapidapi-host': 'wft-geo-db.p.rapidapi.com'
}
});
})
.then(response => response.json())
.then(data2 => {
console.log(data2);
})
.catch(error => console.error(error));
</script>
</body>
</html>
Wrap up
Fetching data from multiple endpoints with the Fetch API can be very useful in many scenarios, especially in applications that require data from various sources. If you want to learn more about Fetch API, we have written a lot of guides on it that you can find here.
FAQs
One way to fetch data from multiple endpoints is by chaining multiple fetch requests together. In this approach, you make a fetch request to the first endpoint and then use the response from that request to make another fetch request to the next endpoint. console. error(error);
How to fetch data from multiple APIs? ›
And when you want to fetch multiple APIs at the same time, you can write like this. fetch('https://jsonplaceholder.typicode.com/todos/1'), fetch('https://jsonplaceholder.typicode.com/photos/1'), fetch('https://jsonplaceholder.typicode.com/albums/1')])const res= await data.
Can one API have multiple endpoints? ›
Software programs typically have multiple API endpoints. For example, Instagram's endpoints include one that enables businesses and creators to measure media and profile interactions, another that lets them moderate comments and their replies, and a third that enables them to discover hashtagged media.
How to fetch multiple endpoints in React? ›
To fetch data with relationships from multiple endpoints, we'll need to make multiple asynchronous requests and then combine the data as needed. Let's continue with our blogging platform example and fetch posts along with their associated user data and comments.
How to fetch data from API using Fetch API? ›
With the Fetch API, you make a request by calling fetch() , which is available as a global function in both window and worker contexts. You pass it a Request object or a string containing the URL to fetch, along with an optional argument to configure the request.
How do I fetch multiple data? ›
One way to fetch data from multiple endpoints is by chaining multiple fetch requests together. In this approach, you make a fetch request to the first endpoint and then use the response from that request to make another fetch request to the next endpoint.
How to fetch data from an endpoint? ›
The fetch() function sends a GET request to the given API endpoint. To wait for the asynchronous operation to complete, use the await keyword. The returned response object contains information about the response, such as its status and headers.
What is the difference between API and endpoint? ›
It's important to note that endpoints and APIs are different. An endpoint is a component of an API, while an API is a set of rules that allow two applications to share resources. Endpoints are the locations of the resources, and the API uses endpoint URLs to retrieve the requested resources.
How many endpoints are in API? ›
An API server can host one or multiple API endpoints, meaning it will accept and process calls directed at those endpoints' URLs. API clients also need to have a URL so that the API server knows where to send its replies, just as Bob and Alice both need a phone number for phone calls between them to work.
Can a single server have multiple endpoints? ›
As demonstrated in the Multiple Endpoints sample, a service can host multiple endpoints, each with different addresses and possibly also different bindings. This sample shows that it is possible to host multiple endpoints at the same address.
The different ways of Fetching the data in a React application are given below:
- Using React Hooks.
- Using JavaScript Fetch API.
- Using async/await.
- Using Axios library.
- Using React query.
How do you fetch data from an endpoint in React? ›
Different Ways to Fetch Data in React
- Use the stale-while-revalidate (SWR) method. This method is used to fetch data from a server and is used in React. ...
- Use the JavaScript Fetch() method. ...
- Use the React Query library. ...
- Use the Axios Library. ...
- Use the useFetch custom hook from react-fetch-hook.
How do I fetch large data in React? ›
Fetching data in React can be done using the useEffect hook. Here's a simple example: 1import React, { useState, useEffect } from 'react'; 2 3const MyComponent = () => { 4 const [data, setData] = useState(null); 5 6 useEffect(() => { 7 fetch('/api/data') 8 .
What is the difference between fetch and fetch API? ›
fetch() lets you make network requests similar to XMLHttpRequest (XHR). The main difference is that the Fetch API uses Promises, which has a simpler API to help you avoid the complicated callbacks in the XMLHttpRequest API. If you've never used Promises before, check out Introduction to JavaScript Promises.
How can I fetch data from API faster? ›
Caching is one of the best ways to improve API performance. If you have requests that frequently produce the same response, a cached version of the response avoids excessive database queries. The easiest way to cache responses is to periodically expire it, or force it to expire when certain data updates happen.
What are the different ways to fetch API? ›
- Fetch API. We can fetch data by using javascript fetch() method. ...
- Axios. Axios is a javascript library that we use to make HTTP requests same as fetch(). ...
- Using async and await. We use Async-Await as it is an asynchronous technique that is operated via an event loop. ...
- Custom Hooks. ...
- React Query.
Can you use multiple APIs at once? ›
API orchestration is the process of integrating two or more applications into a single, unified offering. For example, you can combine API calls into a single frontend, automate processes, or combine multiple internal APIs.
How to make multiple API calls? ›
Create a function to make multiple API calls in parallel. This function should take an array of API endpoints as an input and return an array of responses from the APIs. 3. Call the makeMultipleAPICalls() function to make multiple API calls in a synchronous way.
How do I fetch data from multiple databases? ›
There are various techniques to handling this problem:
- Table Linking and Federation - link tables from one source into another for querying.
- Custom Code - write code and multiple queries to manually combine the data.
- Data Warehousing/ETL - extract, transform, and load the data into another source.
How to extract data from APIs? ›
How to extract the API data
- Step 1: retrieve the API data URL.
- Step 2: create a new, blank Excel document.
- Step 3: paste the API data URL in the Excel document.
- Step 4: Enter the credentials.
- Step 5: load the API data in the Excel.