How to use JavaScript Fetch API to Get Data?


Nowadays, JavaScript is useful for writing frontend and backend code. Also, it is the most widely used programming language.

Furthermore, we need to get the data from other servers while developing real-time applications. We can fetch data from other servers or databases using the API, which stands for the application programming interface.

Here, we will learn various methods to fetch API to get data using JavaScript.

Use the fetch() method

The fetch() is a browser’s method to get the data from the API. It takes the API URL as the first parameter we need to get data and options as a second parameter. The options can contain headers and authentication tokens.

Syntax

Users can use the syntax below to fetch() to get data.

fetch(baseURL)
.then(data => {
   // use data here
}

In the above syntax, baseURL is an API to get data.

Example 1

In the example below, When a user clicks the button, it executes the fetchData() function. Inside the fetchData() function, we have used the fetch() method to fetch data from API. After that, we handled the response and error. Users can see the data we fetched from the API in the output.

<html>
<body>
   <h2>Using the <i> fetch() browser method </i> to fetch data from API</h2>
   <div id = "output"> </div> 
   <button onclick = "fetchData()"> Fetch API to get data </button>
   <script>
      let output = document.getElementById('output');
      function fetchData() {
         fetch('https://dummyjson.com/products/1')
         .then(response => response.json())
         .then(data => {
            output.innerHTML += "id = " + data.id + "<br/>";
            output.innerHTML += "brand = " + data.brand + "<br/>";
            output.innerHTML += "category = " + data.category + "<br/>";
            output.innerHTML += "price = " + data.price + "<br/>";
            output.innerHTML += "rating = " + data.rating + "<br/>";
            output.innerHTML += "stock = " + data.stock + "<br/>";
         })
      }
   </script>
</body>
</html>

Use the axios npm package

The axios is an NPM package that allows developers to interact with the API by making the GET, POST, PUT, etc. requests. Here, we will use the axios to make a GET request to get data in JavaScript.

Syntax

Users can follow the syntax below to use the axios to get data from the API.

axios.get(URL)
.then((response) => {
   // use response
} 

In the above syntax, we have used the axios.get() method to fetch data from the API.

Example 2

In this example, We are resolving the promise using the then()and catch() blocks we get from the server or database. We have utilized the data in the then() block and the error in the catch() block.

<html>
<head>
   <script src ="https://cdnjs.cloudflare.com/ajax/libs/axios/1.2.3/axios.min.js"></script>
</head>
<body>
   <h2>Using the <i> Axios NPM package </i> to fetch data from API</h2>
   <div id = "output"> </div>
   <button onclick = "fetchData()"> Fetch data using Axios </button>
   <script>
      let output = document.getElementById('output');
      function fetchData() {
         axios.get("https://jsonplaceholder.typicode.com/todos/1") 
         .then((response) => {
            output.innerHTML += "userId : " + response.data.userId + "<br/>";
            output.innerHTML += "id : " + response.data.id + "<br/>";
            output.innerHTML += "title : " + response.data.title + "<br/>";
            output.innerHTML += "completed : " + response.data.completed + "<br/>";
         })
         .catch((err) => {
            output.innerHTML += "The error is - " + err + "<br/>";
         })
      }
   </script>
</body>
</html>

Example 3

In the example below, we have used the axios to fetch data with async/await syntax. We have made the getData() function asynchronous. Also, we have used the await keyword with the axios to suspend the execution of the function until we get a response from the API.

<html>
<head>
   <script src ="https://cdnjs.cloudflare.com/ajax/libs/axios/1.2.3/axios.min.js"></script>
</head>
<body>
   <h2>Using the <i> Axios NPM package </i> with Async/await syntax to fetch data from API</h2>
   <div id = "output"> </div>
   <button onclick = "getData()"> get data using Axios </button>
   <script>
      let output = document.getElementById('output');
      async function getData() {
         let response = await
         axios.get("https://jsonplaceholder.typicode.com/todos/1")
         for (let key in response.data) {
            output.innerHTML += key + " - " + response.data[key] + "<br/>";
         }
      }
   </script>
</body>
</html>

Using the XMLHttpRequest web API

The XMLHttpRequest web API allows us to create our module to fetch the data. We can create an object and initialize it with the XMLHttpRequest. After that, we can use that object to open a GET request.

After that, we can invoke a callback function when XMLHttpRequest loads. The callback function can get the response status and return a response or error accordingly.

Syntax

const xmlRequest = new XMLHttpRequest();
xmlRequest.open('GET', apiURL);
xmlRequest.responseType = 'json';
xmlRequest.onload = function () {
   // handle the response from API
}
xmlRequest.send(); 

In the above syntax, we first used the open() method to open a request, and we are handling the response from API using the onload event.

Example 4

In the example below, we have to use the XMLHttpRequest() web API to create a custom module to fetch data from the API. The customRequest() function contains the custom module.

After that, we invoked the customRequest() function by passing the URL as a parameter and used the then() block to resolve the promise returned from the customRequest() function.

<html>
<body>
   <h2>Using the <i> XMLHttpRequest web API </i> to fetch data from API</h2>
   <div id = "output"> </div>
   <button onclick = "getData()"> get data </button>
   <script>
      let output = document.getElementById('output');
      const customRequest = (apiURL) => {
         return new Promise((res, rej) => {
      
            // Create a new Object of XMLHttpRequest
            const xmlRequest = new XMLHttpRequest();
            
            // open a get request
            xmlRequest.open('GET', apiURL);
            
            // set response type
            xmlRequest.responseType = 'json';
            xmlRequest.onload = function () {
               // resolve the promise when we get a successful response
               if (xmlRequest.status == 200) {
                  res(xmlRequest.response);
               } else {
                  
                  // reject promise on error
                  rej(xmlRequest.response);
               }
            };
            
            // send request
            xmlRequest.send();
         }); 
      };
      
      // making the get request from URL
      const getData = async () => {
         try {
            const data = await customRequest(
               'https://dummyjson.com/products/1',
            );
            output.innerHTML += "category = " + data.category + "<br/>";
            output.innerHTML += "price = " + data.price + "<br/>";
            output.innerHTML += "rating = " + data.rating + "<br/>";
            output.innerHTML += "stock = " + data.stock + "<br/>";
         } catch (err) {
            output.innerHTML += "The error is : " + err + "<br/>";
         }
      };
   </script>
</body>
</html> 

We learned three different ways to fetch data from API. The best way is using the fetch() browser’s method, as we don’t need to install any module to use it. Also, users should use all modules with the async/await syntax.

Updated on: 16-Feb-2023

17K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements