How to create a webpage using HTML, CSS, and JavaScript to request data from an API and display it on the webpage

HTML:

 <!DOCTYPE html>
<html>
<head>
<title>API Data Display</title>
</head>
<body>
<h1>API Data</h1>
<div id="data-container"></div>
<script src="main.js"></script>
</body>
</html>


CSS:

body {
font-family: Arial, sans-serif;
text-align: center;
}

#data-container {
margin: 0 auto;
width: 80%;
text-align: left;
}


JavaScript:

//Make a request to the API endpoint
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
//Get the data container element
const dataContainer = document.getElementById('data-container');
//Loop through the data and create a new element for each item
data.forEach(item => {
const newItem = document.createElement('p');
newItem.innerText = JSON.stringify(item);
dataContainer.appendChild(newItem);
});
})
.catch(error => console.error(error));

Note: This is a very basic example and you may want to add error handling and more formatting/styling to your actual implementation.

You also have to make sure that you have the right endpoint url and the right api key if it required.

Similar Posts