Fetch Data from API and Display in HTML using JavaScript Fetch API

Posted by

Get Data from API & Display in HTML

Get Data from API & Display in HTML

Below is the example of fetching data from an API and displaying it in HTML using the JavaScript Fetch API.

// Fetch data from API
fetch(‘https://example.com/api/data’)
.then(response => response.json())
.then(data => {
// Display data in HTML
let dataContainer = document.getElementById(‘data-container’);
dataContainer.innerHTML = ‘

' + JSON.stringify(data, null, 2) + '

‘;
})
.catch(error => {
console.error(‘Error fetching data:’, error);
});

In this example, we are using the fetch() method to make a GET request to the specified API endpoint (‘https://example.com/api/data’). We then use the .then() method to handle the response returned from the API, and the .catch() method to handle any errors that may occur during the request.

Once we have received the data from the API, we use the JavaScript DOM manipulation to display the data in HTML. In this case, we are creating a

 element to display the JSON data returned from the API in a readable format. We then set the innerHTML property of the data-container element to the formatted JSON data using the JSON.stringify() method with 2 for the indent parameter.

This is a simple example of how to fetch data from an API and display it in HTML using the JavaScript Fetch API. You can further customize the display of the data or perform other operations on it as per your requirements. Fetch API is a powerful and flexible way to interact with web APIs and handle asynchronous HTTP requests in JavaScript.