JSON, Fetch API & REST Integration (The Complete Masterclass)
Welcome to Phase 14: JSON and Fetch API! The Fetch API provides a modern, Promise-based interface for requesting network resources across the web. Almost every production web application interacts with backend servers and 3rd-party microservices by exchanging data in JSON (JavaScript Object Notation) format. In this comprehensive masterclass guide, you will learn JSON serialization/deserialization, HTTP REST request methods (GET, POST, PUT, DELETE), Request Headers, Request Body payloads, status code handling, response.ok verification, managing UI Loading States, query string construction, API authentication tokens, and build 5 complete production-grade network applications.
JSON (JavaScript Object Notation) ante servers mariyu clients madhya data exchange cheyyadaniki standard lightweight text format. JSON language-independent (Python, Java, Node.js, Go anni languages JSON ni parse cheyyagalavu):
| JSON Rule | Valid JSON Syntax | Invalid Syntax โ |
|---|---|---|
| Keys must be double-quoted | { "username": "Ravi" } | { username: 'Ravi' } (Single quotes or unquoted keys fail!) |
| Supported Data Types | String, Number, Boolean, Array, Object, null | Functions, undefined, Symbols are NOT allowed! |
"use strict";
const studentObj = {
id: 101,
name: "Ravi",
skills: ["JavaScript", "React"],
active: true
};
// 1. Convert JS Object to JSON String (Serialization)
const jsonString = JSON.stringify(studentObj, null, 2);
console.log("JSON String Output:\n", jsonString);
// 2. Convert JSON String back to JS Object (Deserialization)
const parsedObj = JSON.parse(jsonString);
console.log("Parsed Name:", parsedObj.name); // "Ravi"
| HTTP Method | Purpose | Has Request Body? | CRUD Operation |
|---|---|---|---|
GET | Read data from server | โ No | Read |
POST | Create a brand new record | โ Yes (JSON payload) | Create |
PUT / PATCH | Update existing record (Full / Partial) | โ Yes | Update |
DELETE | Remove resource from database | โ Usually No | Delete |
fetch() returns a Promise that only rejects on network failure (e.g. user offline or DNS failure). Server 404 Not Found or 500 Internal Server Error return chesina kooda Promise resolve avthundhi! Developer eppudu if (!response.ok) throw new Error(...) check cheyyali!
"use strict";
async function loadUsers() {
try {
// Fetch API network call
const response = await fetch("https://jsonplaceholder.typicode.com/users");
// Validate response status (200-299)
if (!response.ok) {
throw new Error("HTTP Error! Status: " + response.status);
}
// Parse JSON stream
const users = await response.json();
console.log("Retrieved Users Count:", users.length);
console.log("First User Name:", users[0]?.name);
} catch (error) {
console.error("Fetch Failed:", error.message);
}
}
loadUsers();
Server ki kottha data pampincheppudu method: "POST", headers: { "Content-Type": "application/json" }, mariyu body: JSON.stringify(data) include cheyyali:
"use strict";
async function createPost(title, body) {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: {
"Content-Type": "application/json; charset=UTF-8",
"Authorization": "Bearer sample_jwt_token_123"
},
body: JSON.stringify({
title: title,
body: body,
userId: 1
})
});
if (!response.ok) throw new Error("Failed to create post!");
const newRecord = await response.json();
console.log("โ
Post Created with ID:", newRecord.id);
} catch (err) {
console.error("Error creating post:", err.message);
}
}
createPost("Mastering JavaScript 2026", "In-depth Fetch API and JSON tutorial.");
Professional frontend applications 3 visual states ni manage chesthayi: Loading Spinner $ ightarrow$ Success Data $ ightarrow$ Error Message:
async function fetchWithUIState() {
const spinner = document.querySelector("#loadingSpinner");
const container = document.querySelector("#dataContainer");
const errorBox = document.querySelector("#errorBox");
try {
spinner.style.display = "block"; // 1. Start Loading
errorBox.textContent = "";
const res = await fetch("https://jsonplaceholder.typicode.com/posts/1");
if (!res.ok) throw new Error("Data not available!");
const data = await res.json();
container.textContent = data.title; // 2. Render Success
} catch (err) {
errorBox.textContent = "โ ๏ธ " + err.message; // 3. Render Error
} finally {
spinner.style.display = "none"; // 4. Always Stop Loading!
}
}
Mastering Fetch API and JSON through 5 complete production projects:
Project 1: Live Weather Dashboard
"use strict";
async function fetchCityWeather(city) {
try {
console.log("Fetching weather for: " + city + "...");
// Mocking weather API response structure
const mockApiUrl = "https://jsonplaceholder.typicode.com/posts/1";
const response = await fetch(mockApiUrl);
if (!response.ok) throw new Error("City not found!");
const data = {
city: city,
temperature: "28ยฐC",
condition: "Sunny",
humidity: "65%"
};
console.log("โ
Weather in " + data.city + ": " + data.temperature + " (" + data.condition + ")");
} catch (err) {
console.error("Weather error:", err.message);
}
}
fetchCityWeather("Hyderabad");
Project 2: Movie Search Engine
async function searchMovies(query) {
try {
const encoded = encodeURIComponent(query);
const url = "https://jsonplaceholder.typicode.com/photos?albumId=1";
const res = await fetch(url);
const results = await res.json();
console.log("Found " + results.length + " movies for query: " + query);
} catch (err) {
console.error("Movie search error:", err.message);
}
}
searchMovies("Inception");
Project 3: GitHub Profile Finder
"use strict";
async function getGitHubUser(username) {
try {
const res = await fetch("https://api.github.com/users/" + username);
if (!res.ok) throw new Error("User " + username + " not found on GitHub!");
const user = await res.json();
console.log("GitHub Profile:", user.name || user.login);
console.log("Public Repos:", user.public_repos);
console.log("Followers:", user.followers);
} catch (err) {
console.error("GitHub API Error:", err.message);
}
}
getGitHubUser("torvalds");
Project 4: Category-Based News Feed
async function loadNewsCategory(category = "technology") {
try {
const res = await fetch("https://jsonplaceholder.typicode.com/posts?_limit=5");
const articles = await res.json();
console.log("Top 5 " + category.toUpperCase() + " Headlines:");
articles.forEach((art, idx) => console.log((idx + 1) + ". " + art.title));
} catch (err) {
console.error("Failed to load news:", err.message);
}
}
loadNewsCategory("tech");
Project 5: Real-Time Currency Converter
"use strict";
async function convertCurrency(amountUSD, targetCurrency = "INR") {
try {
// Exchange Rate calculation
const rates = { INR: 86.5, EUR: 0.92, GBP: 0.79 };
const converted = amountUSD * (rates[targetCurrency] || 1);
console.log("$" + amountUSD + " USD = " + converted.toFixed(2) + " " + targetCurrency);
} catch (err) {
console.error("Conversion error:", err.message);
}
}
convertCurrency(100, "INR");
convertCurrency(250, "EUR");
Run this async Fetch API user loader in our live Node.js / JavaScript compiler:
"use strict";
async function loadUsers() {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/users");
if (!response.ok) {
throw new Error("Request failed");
}
const users = await response.json();
console.log("Loaded " + users.length + " users successfully!");
console.log("First User:", users[0]?.name);
} catch (error) {
console.error(error.message);
}
}
loadUsers();