<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fetch API Data and Display as Table</title>
<style>
table {
width: 100%;
border-collapse: collapse;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
</style>
</head>
<body>
<h2>API Data Displayed as Table</h2>
<div id="table-container"></div> <!-- Container for the table -->
<script>
// Define the API endpoint and the bearer token
const apiEndpoint = "YOUR_API_ENDPOINT_HERE";
const bearerToken = "YOUR_BEARER_TOKEN_HERE";
// Function to fetch data from the API
function fetchData() {
// Setup the request headers with the authorization token
const headers = new Headers({
"Authorization": `Bearer ${bearerToken}`,
"Content-Type": "application/json"
});
// Make the fetch request to the API
fetch(apiEndpoint, { method: "GET", headers: headers })
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
// Call the function to display the data as a table
displayTable(data);
})
.catch(error => {
console.error('There has been a problem with your fetch operation:', error);
});
}
// Function to display JSON data as a table
function displayTable(data) {
// Assume data is an array of objects
// Create table
const table = document.createElement("table");
table.setAttribute("border", "1");
// Add table header
const thead = document.createElement("thead");
const headerRow = document.createElement("tr");
if(data.length > 0){
Object.keys(data[0]).forEach(key => {
const th = document.createElement("th");
th.textContent = key;
headerRow.appendChild(th);
});
}
thead.appendChild(headerRow);
table.appendChild(thead);
// Add table body
const tbody = document.createElement("tbody");
data.forEach(item => {
const row = document.createElement("tr");
Object.values(item).forEach(value => {
const td = document.createElement("td");
td.textContent = value;
row.appendChild(td);
});
tbody.appendChild(row);
});
table.appendChild(tbody);
// Append the table to the document body (or any other container)
document.getElementById('table-container').appendChild(table);
}
// Call the function to fetch data and display it
fetchData();
</script>
</body>
</html>