JavaScript : Fetching and Displaying API Data using JavaScript

Java Script @ Freshers.in

This article presents a concise guide to retrieving data from an external API using JavaScript’s fetch() method. This data is then dynamically displayed on an HTML page. It covers the essential concepts, such as Promises, JSON parsing, and DOM manipulation in a straightforward and practical manner. This approach enables developers to effectively pull and display information from various API endpoints, thus enriching the content and functionality of their web applications. Please note that the functionality of the code relies on the API endpoint being accessible and enabled for CORS from the domain hosting the HTML file.

You can use JavaScript’s fetch() API to retrieve data from an external API. Here’s an example of a complete HTML page that fetches data from your specified URL and presents it in a simple format:

<!DOCTYPE html>
<html>

<head>
    <title>Fetching API Data</title>
    <style>
        .container {
            width: 50%;
            margin: auto;
            padding: 20px;
        }

        .data {
            margin-bottom: 20px;
            border: 1px solid #ccc;
            padding: 10px;
        }
    </style>
</head>

<body>
    <div class="container">
        <h1>API Data:</h1>
        <div id="apiData">
            <!-- Data from the API will be inserted here -->
        </div>
    </div>

    <script>
        // The URL of the API you want to fetch
        let url = 'http://www.freshers.in/api/';

        // Use the fetch API to get the data
        fetch(url)
            .then(response => response.json()) // Parse the data as JSON
            .then(data => {
                let apiDataDiv = document.getElementById('apiData');

                // Iterate through the data and create a div for each item
                for (let item of data) {
                    let div = document.createElement('div');
                    div.className = 'data';
                    div.innerText = JSON.stringify(item, null, 2);
                    apiDataDiv.appendChild(div);
                }
            })
            .catch(error => {
                console.error('Error:', error);
            });
    </script>
</body>

</html>

The fetch() function is used to retrieve data from the API. This function returns a Promise.
The .then() function is used to handle the Promise. Once the data is retrieved, it is converted into JSON using the response.json() function.
Another .then() function is used to handle the JSON data. This function takes the JSON data, iterates through it, creates a new div for each item in the data, and adds it to the apiData div in the HTML.
The catch() function is used to handle any errors that might occur during the fetch operation.

Get more articles on Java Script

Author: user

Leave a Reply