In this guide, we'll explore how to make an API call from a web page and extract JSON data to display it dynamically on the webpage.
First, let's create an HTML file with a div
element having the id userData
:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Making an API Call</title> </head> <body> <!-- Div element to hold user data --> <div id="userData"></div> <!-- JavaScript code will go here --> </body> </html>
Next, we'll write JavaScript code to fetch data from the API and display it on the webpage. We'll utilize the DOMContentLoaded
event to ensure that the JavaScript code executes after the DOM content is fully loaded:
document.addEventListener('DOMContentLoaded', () => { const apiUrl = 'https://api.example.com/users'; // Fetch data from the API fetch(apiUrl) .then(response => { if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } return response.json(); }) .then(data => { // Display data displayUserData(data); }) .catch(error => { console.error('Fetch error:', error); }); // Function to display user data function displayUserData(userData) { const userDataContainer = document.getElementById('userData'); userData.forEach(user => { // Create a paragraph for each user const userParagraph = document.createElement('p'); userParagraph.textContent = `Name: ${user.name}, Email: ${user.email}`; // Append the paragraph to the container userDataContainer.appendChild(userParagraph); }); } });
HTML Markup: We create a simple HTML file with a div
element to hold the user data.
JavaScript Logic:
fetch()
to make an API call to the specified apiUrl
.displayUserData()
function to render the data on the webpage.displayUserData()
function creates a paragraph element for each user and appends it to the userData
container div.This setup allows us to dynamically fetch and display JSON data from an API on a web page.