Featured
- Get link
- X
- Other Apps
๐ก Day 37 — Fetch API & JSON Data Handling
๐ก Day 37 — Fetch API & JSON Data Handling
Hi Guys Welcome to Day 37 ๐ You’ve already learned about Web APIs — now it’s time to connect your web apps to the internet. Today, you’ll learn to use the Fetch API to get real data from web servers and work with JSON (JavaScript Object Notation). This is the foundation of dynamic apps like weather dashboards, stock trackers, and movie databases.
๐ 1️⃣ What is Fetch API?
The Fetch API is a modern, built-in browser feature that lets you make HTTP requests — GET data from a server, POST new info, update records, and delete items — all using JavaScript.
fetch("https://jsonplaceholder.typicode.com/posts")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("Error:", error));
It returns a Promise, so you can chain .then() and .catch() to handle asynchronous responses.
๐ก 2️⃣ The Response Lifecycle
When you call fetch():
- It sends a request to the server.
- The server replies with a response (status + body).
- You process the data (usually JSON).
๐ง 3️⃣ Handling JSON Responses
Most modern APIs send data in JSON — a structured, text-based format. Here’s how to fetch and display JSON data properly.
async function getPosts() {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/posts");
const data = await response.json();
console.log("Fetched posts:", data.slice(0, 3)); // show first 3
} catch (error) {
console.error("Failed to fetch:", error);
}
}
getPosts();
๐ฆ 4️⃣ Displaying Data on a Webpage
Let’s fetch posts and show them inside HTML dynamically.
async function displayPosts() {
const container = document.getElementById("posts");
const res = await fetch("https://jsonplaceholder.typicode.com/posts");
const posts = await res.json();
posts.slice(0, 5).forEach(post => {
const div = document.createElement("div");
div.style.marginBottom = "15px";
div.innerHTML = `${post.title}
${post.body}
`;
container.appendChild(div);
});
}
displayPosts();
This is exactly how news feeds, blog pages, or YouTube video lists are rendered!
⚙️ 5️⃣ Sending Data (POST Request)
You can also send data to a server — for example, submitting a form.
fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title: "New Post", body: "Learning Fetch!", userId: 1 })
})
.then(res => res.json())
.then(data => console.log("Created:", data));
๐งฎ 6️⃣ Common HTTP Status Codes
- 200 → OK ✅
- 201 → Created
- 400 → Bad Request
- 404 → Not Found ❌
- 500 → Server Error ๐ฅ
๐ง 7️⃣ Practice Project Idea
- Build a “User Directory” that fetches user names from an API.
- Display the names with email and address.
- Add a “Refresh” button to reload data dynamically.
๐ฏ Summary
You just learned how real apps talk to servers using Fetch API and JSON.
This is the basis of all data-driven JavaScript apps.
Next, you’ll learn how to handle API errors and asynchronous issues gracefully with try...catch and proper validation.
Popular Posts
๐ Day 27: Bootstrap Mini Project – Responsive Portfolio Page
- Get link
- X
- Other Apps
๐จ Day 2: Headings, Paragraphs & Text Formatting
- Get link
- X
- Other Apps
Comments
Post a Comment