How to display data from an API in a dynamic table using JavaScript and Bootstrap

Display data from an API in a dynamic table using JavaScript to fetch and populate the table.


Displaying data from an API in a dynamic table enhances user experience by providing real-time information in a structured format. This tutorial will guide you through the process of integrating an API with an HTML table, using JavaScript to fetch and display data.

Prerequisites

  • Basic Knowledge of HTML and CSS: Understanding of HTML elements and basic styling.
  • JavaScript Fundamentals: Familiarity with functions, asynchronous operations, and DOM manipulation.
  • An API Endpoint: Access to an API that returns data in JSON format. This could be your own API or a public one.

Tutorial Overview

We will:

  1. Set up the HTML structure for the table.
  2. Write JavaScript code to fetch data from an API.
  3. Dynamically populate the table with the fetched data.
  4. Ensure the table is responsive and styled appropriately.

Step 1: Set Up the HTML Structure

Create an HTML file and add the following code to set up the table structure.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Dynamic Table with API Data</title>
  <!-- Include Bootstrap CSS for styling (optional) -->
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://demos.creative-tim.com/material-dashboard-pro/assets/css/material-dashboard.min.css?v=2.2.2" rel="stylesheet">
</head>
<body>

  <div class="container mt-5">
    <div class="card">
      <div class="table-responsive">
        <table class="table align-items-center mb-0" id="data-table">
          <thead>
            <tr>
              <th>Author</th>
              <th>Function</th>
              <th class="text-center">Technology</th>
              <th class="text-center">Employed</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            <!-- Data will be inserted here dynamically -->
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <!-- Include Bootstrap JS and dependencies (optional) -->
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
  <!-- Your custom script will go here -->
</body>
</html>

Notes:

  • The table has an id of data-table, which we’ll use to select it in our JavaScript code.
  • Bootstrap CSS is included for basic styling. You can omit it or replace it with your own styles.

Step 2: Write the JavaScript to Fetch Data from the API

Below the existing code, before the closing </body> tag, add a <script> tag where we’ll write our JavaScript.

<script>
  // Function to fetch data from the API and populate the table
  async function fetchData() {
    try {
      const response = await fetch('YOUR_API_ENDPOINT'); // Replace with your API endpoint
      const data = await response.json();

      const tableBody = document.querySelector('#data-table tbody');
      tableBody.innerHTML = ''; // Clear existing data if any

      data.forEach(user => {
        const row = document.createElement('tr');

        row.innerHTML = `
          <td>
            <div class="d-flex px-2 py-1">
              <div>
                <img src="${user.avatar}" class="avatar avatar-sm me-3" alt="Avatar">
              </div>
              <div class="d-flex flex-column justify-content-center">
                <h6 class="mb-0 text-xs">${user.name}</h6>
                <p class="text-xs text-secondary mb-0">${user.email}</p>
              </div>
            </div>
          </td>
          <td>
            <p class="text-xs font-weight-bold mb-0">${user.position}</p>
            <p class="text-xs text-secondary mb-0">${user.department}</p>
          </td>
          <td class="align-middle text-center text-sm">
            <span class="badge badge-sm ${user.status === 'Online' ? 'bg-success' : 'bg-secondary'}">${user.status}</span>
          </td>
          <td class="align-middle text-center">
            <span class="text-secondary text-xs font-weight-normal">${user.employmentDate}</span>
          </td>
          <td class="align-middle">
            <a href="#!" class="text-secondary font-weight-normal text-xs" data-bs-toggle="tooltip" title="Edit user">
              Edit
            </a>
          </td>
        `;
        
        tableBody.appendChild(row);
      });
    } catch (error) {
      console.error('Error fetching data:', error);
    }
  }

  // Call fetchData to load the table data when the page loads
  window.onload = fetchData;
</script>

Explanation:

  • async function fetchData(): An asynchronous function that allows us to use await for promises.
  • fetch(‘YOUR_API_ENDPOINT’): Replace 'YOUR_API_ENDPOINT' with the URL of your API.
  • response.json(): Parses the JSON data returned by the API.
  • document.querySelector(‘#data-table tbody’): Selects the <tbody> of the table to insert rows.
  • data.forEach(user => { … }): Iterates over each item in the data array to create table rows.

Step 3: Replace the Placeholder API with Your Own

In the script, replace 'YOUR_API_ENDPOINT' with the actual URL of your API. For example:

const response = await fetch('https://api.example.com/users');

Ensure that your API returns data in the following format or adjust the code accordingly:

[
 {
    "avatar": "URL_TO_IMAGE",
    "name": "User Name",
    "email": "[email protected]",
    "position": "Position Title",
    "department": "Department Name",
    "status": "Online or Offline",
    "employmentDate": "DD/MM/YY"
  },
  ...
]

Step 4: Test the Implementation

  • Run the HTML File: Open the HTML file in a web browser.
  • Check for Data: The table should populate with data fetched from your API.
  • Verify Console for Errors: Open the browser’s developer console to check for any errors.

Step 5: Handling CORS Issues (If Any)

If you encounter a Cross-Origin Resource Sharing (CORS) error, you might need to adjust your API settings to allow requests from your domain or use a proxy.

Complete Code Example

Here’s the full HTML code with the JavaScript included:

Author Function Technology Employed
John Michael

[email protected]

Manager

Organization

Online 23/04/18 Edit
Alexa Liras

[email protected]

Programator

Developer

Offline 11/01/19 Edit
Laurent Perrier

[email protected]

Executive

Projects

Online 19/09/17 Edit
Michael Levi

[email protected]

Programator

Developer

Online 24/12/08 Edit
Richard Gran

[email protected]

Manager

Executive

Offline 04/10/21 Edit
Miriam Eric

[email protected]

Programtor

Developer

Offline 14/09/20 Edit
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Dynamic Table with API Data</title>
  <!-- Include Bootstrap CSS for styling (optional) -->
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://demos.creative-tim.com/material-dashboard-pro/assets/css/material-dashboard.min.css?v=2.2.2" rel="stylesheet">
</head>
<body>

  <div class="container mt-5">
    <div class="card">
      <div class="table-responsive">
        <table class="table align-items-center mb-0" id="data-table">
          <thead>
            <tr>
              <th>Author</th>
              <th>Function</th>
              <th class="text-center">Technology</th>
              <th class="text-center">Employed</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            <!-- Data will be inserted here dynamically -->
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <!-- Include Bootstrap JS and dependencies (optional) -->
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>

  <script>
    // Function to fetch data from the API and populate the table
    async function fetchData() {
      try {
        const response = await fetch('YOUR_API_ENDPOINT'); // Replace with your API endpoint
        const data = await response.json();

        const tableBody = document.querySelector('#data-table tbody');
        tableBody.innerHTML = ''; // Clear existing data if any

        data.forEach(user => {
          const row = document.createElement('tr');

          row.innerHTML = `
            <td>
              <div class="d-flex px-2 py-1">
                <div>
                  <img src="${user.avatar}" class="avatar avatar-sm me-3" alt="Avatar">
                </div>
                <div class="d-flex flex-column justify-content-center">
                  <h6 class="mb-0 text-xs">${user.name}</h6>
                  <p class="text-xs text-secondary mb-0">${user.email}</p>
                </div>
              </div>
            </td>
            <td>
              <p class="text-xs font-weight-bold mb-0">${user.position}</p>
              <p class="text-xs text-secondary mb-0">${user.department}</p>
            </td>
            <td class="align-middle text-center text-sm">
              <span class="badge badge-sm ${user.status === 'Online' ? 'bg-success' : 'bg-secondary'}">${user.status}</span>
            </td>
            <td class="align-middle text-center">
              <span class="text-secondary text-xs font-weight-normal">${user.employmentDate}</span>
            </td>
            <td class="align-middle">
              <a href="#!" class="text-secondary font-weight-normal text-xs" data-bs-toggle="tooltip" title="Edit user">
                Edit
              </a>
            </td>
          `;
          
          tableBody.appendChild(row);
        });
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    }

    // Call fetchData to load the table data when the page loads
    window.onload = fetchData;
  </script>
</body>
</html>

Additional Tips

  • Styling: Feel free to customize the styling of the table and its contents to match your application’s theme.
  • Error Handling: Enhance the error handling in the fetchData function to provide user feedback if the data fails to load.
  • Pagination and Sorting: For large datasets, consider implementing pagination and sorting functionality.
  • Security: If your API requires authentication, ensure you handle API keys or tokens securely.

Conclusion

You have successfully created a dynamic table that fetches and displays data from an API using JavaScript. This approach can be extended to various types of data and integrated into larger applications to enhance data presentation and user interaction.