Monday, March 10, 2025

Html Module 58

  Module 58: Preparing HTML for APIs and JSON

Module Overview:

This module focuses on integrating HTML with APIs and JSON data. It covers how to prepare HTML documents to handle API responses, structure data efficiently, and dynamically update the DOM with JSON. By the end of this module, learners will be able to fetch JSON data from APIs, manipulate it, and display it in an interactive way.








Learning Objectives:

By completing this module, learners will be able to:

Understand the role of APIs and JSON in web applications.

Prepare HTML to handle API responses dynamically.

Use JavaScript to fetch and display JSON data in HTML.

Implement best practices for structuring and managing JSON data.

Work with real-time API data and update the UI efficiently.


1. Understanding APIs and JSON in Web Development

What is an API?

An Application Programming Interface (API) allows applications to communicate with each other. In web development, APIs are used to fetch and send data between the client and a server.

What is JSON?

JavaScript Object Notation (JSON) is a lightweight data format that is easy for humans to read and write and easy for machines to parse and generate. It is the standard format used for API responses.

Example JSON Data:

json

code

{ "user": { "id": 1, "name": "John Doe", "email": "john@example.com" } }


2. Preparing HTML for API and JSON Integration

Step 1: Setting Up the HTML Structure







Create an HTML file with a basic structure to display API data.

html

 code

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>API and JSON Integration</title> <style> body { font-family: Arial, sans-serif; margin: 20px; padding: 20px; } .user-info { border: 1px solid #ccc; padding: 10px; width: 300px; } </style> </head> <body> <h2>User Information</h2> <button id="fetchUser">Fetch User</button> <div class="user-info" id="userData"> <!-- User data will be displayed here --> </div> <script src="script.js"></script> </body> </html>

Explanation:

A button (#fetchUser) is provided for fetching API data.

A div (#userData) is created to display user details dynamically.

The script is linked to script.js where we will handle API requests.


3. Writing JavaScript to Fetch and Display JSON Data

Step 2: Writing the JavaScript Code

Create a script.js file to fetch and display API data dynamically.








javascript

code

document.getElementById("fetchUser").addEventListener("click", fetchUserData); function fetchUserData() { const apiUrl = "https://jsonplaceholder.typicode.com/users/1"; // Sample API fetch(apiUrl) .then(response => response.json()) // Convert response to JSON .then(data => { displayUserData(data); }) .catch(error => console.error("Error fetching data:", error)); } function displayUserData(user) { const userDataDiv = document.getElementById("userData"); userDataDiv.innerHTML = ` <p><strong>ID:</strong> ${user.id}</p> <p><strong>Name:</strong> ${user.name}</p> <p><strong>Email:</strong> ${user.email}</p> <p><strong>Phone:</strong> ${user.phone}</p> <p><strong>Website:</strong> <a href="http://${user.website}" target="_blank">${user.website}</a></p> `; }

Explanation:

Event Listener: Listens for a click on the "Fetch User" button.

Fetch API:

Calls a sample API (jsonplaceholder.typicode.com/users/1).

Converts the response to JSON format.

Calls displayUserData() function to show the data in HTML.

Updating the DOM:

The displayUserData() function updates the #userData div with user information.


4. Handling API Data Efficiently

Best Practices for API and JSON Handling:








✅ Use Async/Await for Better Readability

Instead of .then(), use async and await for cleaner code.

javascript

code

async function fetchUserData() { try { const response = await fetch("https://jsonplaceholder.typicode.com/users/1"); const data = await response.json(); displayUserData(data); } catch (error) { console.error("Error fetching data:", error); } }

✅ Validate API Data Before Displaying

Ensure data exists before displaying it.

javascript

code

function displayUserData(user) { if (!user || !user.name) { document.getElementById("userData").innerHTML = "<p>No data available</p>"; return; } document.getElementById("userData").innerHTML = `<p><strong>Name:</strong> ${user.name}</p>`; }

✅ Handle Loading States

Show a loading message while fetching data.

javascript

code

async function fetchUserData() { const userDataDiv = document.getElementById("userData"); userDataDiv.innerHTML = "<p>Loading...</p>"; try { const response = await fetch("https://jsonplaceholder.typicode.com/users/1"); const data = await response.json(); displayUserData(data); } catch (error) { userDataDiv.innerHTML = "<p>Error loading data</p>"; } }


5. Exercises & Practical Implementation

Exercise 1: Fetch and Display a List of Users


Modify the script to fetch and display a list of users instead of a single user.

Exercise 2: Post JSON Data to an API

Modify the script to send JSON data to an API using fetch() and POST method.

javascript

code

async function createUser() { const newUser = { name: "Jane Doe", email: "jane@example.com" }; const response = await fetch("https://jsonplaceholder.typicode.com/users", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(newUser) }); const data = await response.json(); console.log("User Created:", data); } createUser();

Exercise 3: Implement Search Functionality

Allow users to search and display user details by entering an ID in an input field.


6. Summary and Key Takeaways

APIs provide data in JSON format, which needs to be fetched and displayed dynamically in HTML.

     

              


Fetch API and async/await help retrieve and handle JSON data.

Always validate API responses and handle errors properly.

Use event listeners and dynamic DOM updates to display API data interactively.

Implement best practices like loading indicators and error messages for a better user experience.


7. Lecture Preparation and Teaching Guide

Lecture Structure:

Introduction (10 mins) – Explain APIs and JSON basics.

Setting Up HTML (15 mins) – Create a basic UI.

Fetching JSON Data (20 mins) – Write JavaScript to fetch and display API data.

Handling API Data (20 mins) – Validate data, manage loading states.

Practical Exercises (30 mins) – Implement advanced fetching and posting data.

Q&A and Recap (15 mins)


This module ensures students gain practical experience in handling APIs and JSON in web development.


No comments:

Post a Comment

How Developers Create Responsive Bootstrap Popup Modals in Modern Websites

  Bootstrap Modal Tutorial with Responsive Design and JavaScript Validation Create Responsive Popup Modal in Bootstrap with Step-by-Step Exp...