Fetching data from an API and displaying it on a webpage is a foundational skill for any web developer. In this blog post, we’ll guide you through a simple example of fetching data from a REST API and dynamically outputting it on your webpage using JavaScript.
This example covers:
- How to fetch data from an API endpoint.
- Parsing the response to JSON format.
- Dynamically updating the webpage with the fetched data.
- Gracefully handling errors.
Let’s dive into the implementation!
The Full Code Example
Below is the complete HTML file that fetches data from an API endpoint and displays it on a webpage.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>API Data Fetch</title>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
}
#data {
margin-top: 20px;
white-space: pre-wrap;
background-color: #f4f4f4;
padding: 10px;
border: 1px solid #ddd;
border-radius: 5px;
}
#error {
margin-top: 20px;
color: red;
font-weight: bold;
}
</style>
</head>
<body>
<h1>API Data Fetch Example</h1>
<button id="fetchData">Fetch Data</button>
<div id="data"></div>
<div id="error"></div>
<script>
document.getElementById('fetchData').addEventListener('click', () => {
const dataContainer = document.getElementById('data');
const errorContainer = document.getElementById('error');
// Clear previous data and errors
dataContainer.textContent = '';
errorContainer.textContent = '';
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
})
.then(parsedData => {
dataContainer.textContent = JSON.stringify(parsedData, null, 2);
})
.catch(error => {
errorContainer.textContent = `Error fetching data: ${error.message}`;
});
});
</script>
</body>
</html>
Explaining the Code
1. HTML Structure
- A button (
Fetch Data
) triggers the API call when clicked. - Two
<div>
elements (#data
and#error
) display the fetched data and errors, respectively.
2. JavaScript Logic
- Event Listener:
Theclick
event listener on the button triggers the fetch operation. - Fetching Data:
Thefetch()
function sends a GET request to the API endpoint (https://api.example.com/data
). - Parsing Response:
After receiving the response, it’s converted to a JavaScript object or array using.json()
. - Displaying Data:
The fetched data is displayed in the#data
container in a readable format usingJSON.stringify()
. - Error Handling:
If an error occurs during the fetch operation or while parsing the response, it is caught and displayed in the#error
container.
3. Styling
- The data and error messages are styled for better readability using CSS.
- The
white-space: pre-wrap;
CSS rule ensures that the JSON data retains its formatting.
How to Run the Code
- Save the above code to a file (e.g.,
index.html
). - Replace the placeholder URL
https://api.example.com/data
with the actual API endpoint you want to fetch data from. - Open the file in a web browser.
- Click the “Fetch Data” button to see the fetched data displayed on the webpage.
Why This Example is Useful
- API Integration:
This is a practical introduction to working with REST APIs in JavaScript. - Dynamic Content:
Learn how to dynamically update the DOM based on fetched data. - Error Handling:
Understand how to handle errors gracefully to improve the user experience. - Foundational Skill:
Fetching and displaying API data is a common requirement in modern web applications.
Next Steps
Here are some ideas to expand this project:
- Add a loading spinner while fetching the data.
- Display specific attributes from the JSON response instead of the entire object.
- Use a framework like React or Vue.js to manage the dynamic rendering of API data.
By following this tutorial, you’ve created a functional webpage that interacts with an API and displays the fetched data. This skill will open the door to building more complex web applications and integrating real-world data into your projects.
