4. Interactive Apps, Storage & APIs
JSON, Fetch API & Async/Await Explained
Talk to live backend APIs cleanly in JavaScript: understand synchronous vs async code, Promises, async/await, GET vs POST fetch requests, response.ok checks, and loading states.
- Understand JSON syntax and how synchronous vs asynchronous JavaScript works
- Request live data cleanly using fetch(), async, and await
- Handle loading, HTTP 404/500 response.ok errors, and network failures gracefully
Real web applications rarely store every movie, weather report, or user profile inside static HTML files. Instead, the frontend asks a backend API for live data over HTTPS using fetch(), receives a clean JSON payload, and updates the DOM without refreshing the browser tab.
What Is JSON?
JSON (JavaScript Object Notation) is the universal data format spoken across web APIs, Python backends, mobile apps, and databases. It looks nearly identical to JavaScript objects and arrays, with two strict rules:
- All property keys must use double quotes (
"academy"). - No trailing commas after the last item, and no comments allowed.
{
"academy": "Yadav Academy",
"free": true,
"tracks": ["Python", "SQL", "Git", "Web Dev"]
}Synchronous vs Asynchronous Code (async / await)
1. Call fetch(url)
Returns pending Promise
2. Network Wait (Non-Blocking)
UI stays smooth at 60fps
3. Check res.ok & .json()
Handle 404/500 safely
4. Render DOM
Update UI or catch error
While fetch() waits for the network in the background, the browser UI stays interactive (scrolling, clicking). When the response arrives, await resumes your function cleanly.
Normally, JavaScript runs one line immediately after another (synchronous). However, talking to a server across the internet might take 300 milliseconds—if JavaScript froze the whole browser tab waiting, scrolling and animations would lock up completely!
So fetch() returns a Promise—a placeholder saying "I am going to get this data; carry on keeping the UI responsive, and notify me when it arrives."
Modern async / await syntax lets you read Promise-based code cleanly top-to-bottom without messy nested callbacks:
async function loadGitHubUser(username) {
const statusEl = document.querySelector("#status");
statusEl.textContent = "Loading profile...";
try {
const response = await fetch(`https://api.github.com/users/${username}`);
if (!response.ok) {
throw new Error(`Server returned HTTP ${response.status}`);
}
const user = await response.json();
statusEl.textContent = `${user.name || user.login} — ${user.public_repos} repos`;
} catch (error) {
statusEl.textContent = `Could not load profile: ${error.message}`;
} finally {
console.log("Finished API request attempt.");
}
}Look closely at the three essential safety habits inside that function:
- UI Loading State first: Show
"Loading profile..."immediately beforeawait fetch(...)so users know something happened. - Check
if (!response.ok):fetch()treats HTTP404 Not Foundor500as a completed response, NOT a network crash! Checking!response.okcatches bad status codes cleanly beforeresponse.json()fails. try / catch / finally: Catches offline Wi-Fi errors (Failed to fetch) or thrown HTTP errors cleanly without crashing the rest of your app, whilefinallyhides loading spinners whether the call succeeded or failed.
By default, fetch(url) sends a GET request. When submitting new data (like creating a task), pass an options object with method: "POST", headers: { "Content-Type": "application/json" }, and body: JSON.stringify(payload).
Try It Live: Understanding Async Promises & JSON
Run this simulated API fetch playground to observe execution order (1 -> 3 -> 2!) and watch how async / await waits gracefully for JSON parsing:
Click “Run Code” to execute this snippet right in your browser.
Quick Checkpoints
What happens if an API returns an HTTP 404 Not Found status to fetch()?
When sending JSON data in a POST request with fetch(), which header tells the backend server how to parse the body?