How to Fetch Data from API and Display It in an HTML Table

How to fetch Data from API in javascript

Fetching data from an API is a common task in web development. In this tutorial, we’ll explore how to fetch data from API in JavaScript using JavaScript’s fetch API method and display it in an HTML table. Follow along to learn the process step-by-step! 🙂

Introduction to Fetch API

The fetch API is a modern interface that allows you to make HTTP requests to web servers directly from your web browser.

fetch("https://api.example.com/data")
  .then((response) => response.json())
  .then((data) => console.log(data))
  .catch((error) => console.error("Error:", error));

The fetch() method always returns a promise, which can be resolved or rejected. We’ll use async and await in this tutorial to handle these promises more effectively.

Using Async and Await

To make handling promises more straightforward, JavaScript offers the async and await keywords. These enable you to write asynchronous, promise-based code in a cleaner, more readable manner.

we’ll be using these features to fetch data from a dummy API and display it in a neatly formatted HTML table.

Here is the dummy API we’ll use:

'https://dummyjson.com/products'

Setup the project

Before we dive into fetching data from fetch API in JavaScript and displaying it in an HTML table, let’s set up our project. First, create a index.html file in your project directory. Then, create a folder named “js” and within this folder, create a script.js file. Make sure to link this JavaScript file to your index.html by adding <script src="js/script.js"></script> before the closing </body> tag. Now that we have our basic setup ready, we can start writing the code to fetch data and display it in an HTML table.

Fetching Data with Async and Await

Let’s write the function to fetch data from API and display it on the console

async function displayData(api) {
  let apiDataResponse = await fetch(api);
  let data = await apiDataResponse.json();
  console.log(data.products);
}

displayData("https://dummyjson.com/products");

Explanation

We created an asynchronous function displayData. The keyword async before the function makes the function return a promise.

We then created a variable called apiDataResponse. The keyword await makes JavaScript wait until that promise settles and returns its result.

The fetch() method takes two arguments:

  • A URL string or a request object.
  • An optional argument that includes information regarding the request you want to make to the database or API.

The async function pauses until the response is complete. When the response is completed, the apiDataResponse variable is assigned the response object of the request.

Now, apiDataResponse holds the data in multiple formats. apiDataResponse.json() is a method that lets you extract a JSON object from the response. The method returns a promise, so you have to wait for the JSON using await apiDataResponse.json();

The data variable now holds the product array, which you can easily check using the console.

Modifying the above function to display the data in an HTML table

async function displayData(api) {

    let tbody = document.getElementById('myTable');
    let rows = '';
    let apiDataResponse = await fetch(api);
    let data = await apiDataResponse.json();

    //console.log(data.products)
    let prod = data.products;
    for (let i = 0; i < prod.length; i++) {
        rows += `<tr><td><img src="${prod[i].thumbnail}" width="200px" height="150px" alt="img"/></td>
        <td>${prod[i].title}</td>
        <td>${prod[i].brand}</td>
        <td>${prod[i].category}</td>
        <td>${prod[i].description}</td>
        <td>${prod[i].price}</td></tr>`

    }
    tbody.innerHTML = rows;

}

displayData('https://dummyjson.com/products');

HTML Structure

open the index.html file and paste the code below into it.

<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
    <meta charset="utf-8">
    <title>JavaScript</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css">
</head>

<body>
    <div class="container mt-3">
        <h2>Products Table</h2>

        <br>
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th>Thumbnail</th>
                    <th>Product Title</th>
                    <th>Brand</th>
                    <th>Description</th>
                    <th>Category</th>
                    <th>Price</th>

                </tr>
            </thead>
            <tbody id="myTable">

            </tbody>
        </table>

    </div>
    <script type="text/javascript" src="js/script.js"></script>
</body>


</html>

Final Result

howtofetchdatainjavascriptimage

Conclusion

Congratulations! You have successfully fetched data from an API and displayed it in an HTML table. I hope you found this tutorial helpful.

Follow for more! In the next post, I’ll show you how to create a search function for this product table.

See you in the next post! Keep learning and exploring!

1 thought on “How to Fetch Data from API and Display It in an HTML Table”

  1. Pingback: How to Filter Data in an HTML Table using JavaScript

Leave a Comment

Your email address will not be published. Required fields are marked *