Fetch API, REST Requests, JSON & Loading States
1. Simple Definition
Fetch API browser ka modern built-in tool hai jiske zariye JavaScript internet par kisi bhi server (REST API) ko HTTP requests bhej sakti hai aur data (JSON format me) receive kar sakti hai — wo bhi bina page ko refresh kiye! Ye poori tarah Promise-based hai.
2. Real-Life Analogy
• Aap (Browser/Client): Table par baithkar menu se dish select karte hain (Request).
• Waiter (Fetch API): Aapka order lekar kitchen (Server) tak jata hai aur wahan se cooked khana plate me lekar aapke paas aata hai (Response).
• JSON Format: Khana plate me arranged tareeqe se serve hota hai taaki aap aasaani se kha sakein!
3. Why Do We Need It?
Purane zamane me naya data dekhne ke liye poora web page dobara reload hota tha. Fetch API ki wajah se Instagram feed scroll karte waqt naye posts aate rehte hain, weather widgets live temperature dikhate hain, aur search box me type karte hi live suggestions aate hain.
4. Syntax: GET & POST Requests
// 1. Basic HTTP GET Request
async function getProducts() {
try {
const res = await fetch('https://dummyjson.com/products?limit=3');
// CRITICAL: Check if HTTP status is 200-299
if (!res.ok) {
throw new Error(`HTTP Error! Status: ${res.status}`);
}
const data = await res.json(); // Second await for parsing stream to JSON
console.log("Products list:", data.products);
} catch (error) {
console.error("Network ya Server fail:", error.message);
}
}
// 2. HTTP POST Request (Sending data to server)
async function createNewPost(postData) {
try {
const res = await fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json' // Server ko batana ki data JSON me hai
},
body: JSON.stringify(postData) // Object ko string me convert karna
});
const result = await res.json();
console.log("Created successfully with ID:", result.id);
} catch (err) {
console.error("POST request failed:", err);
}
}
5. Basic Example: Complete Production-Grade Pattern with Loading State
async function loadUserData(userId) {
const spinner = document.getElementById('loading-spinner');
const userCard = document.getElementById('user-card');
const errorAlert = document.getElementById('error-box');
// STEP 1: UI state - Start Loading
spinner.style.display = 'block';
errorAlert.style.display = 'none';
try {
// STEP 2: Make Network Request
const response = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`);
// STEP 3: Validate Status
if (!response.ok) {
if (response.status === 404) throw new Error("User nahi mila (404 Not Found)!");
throw new Error(`Server error (${response.status})`);
}
// STEP 4: Parse & Render Data
const user = await response.json();
userCard.innerHTML = `<h3>${user.name}</h3><p>📧 ${user.email}</p><p>🏢 ${user.company.name}</p>`;
} catch (err) {
// STEP 5: Handle Failures
errorAlert.textContent = `❌ ${err.message}`;
errorAlert.style.display = 'block';
} finally {
// STEP 6: ALWAYS stop the spinner (Success ya Error dono cases me!)
spinner.style.display = 'none';
}
}
6. Output / Interactive Live Fetch Simulator
7. Code Explanation: HTTP Status Code Matrix
| Status Code | Meaning | Kya Hua? (Hinglish Me) |
|---|---|---|
200 OK |
Success | Request successful, data aa gaya. |
201 Created |
Resource Created | Naya post ya user database me successfully add ho gaya (POST request). |
400 Bad Request |
Client Error | Client ne galat syntax ya missing fields bhej di. |
401 / 403 |
Unauthorized / Forbidden | Token missing hai ya aapke paas is route ko access karne ki permission nahi hai. |
404 Not Found |
Missing Resource | Jo URL ya ID mangi gayi thi wo server par exist nahi karti. |
500 Server Error |
Backend Crash | Backend code me bug aa gaya ya database down ho gaya. |
8. Real-World Example
Hamari website ke Project #14 (Weather Dashboard) me jab aap kisi shahar ka naam daalte hain, toh Fetch API us shahar ke coordinates lekar Open-Meteo REST API ko call karti hai aur realtime temperature screen par dikhati hai.
9. Common Mistakes
Sabse bada interview bug: fetch() tab tak catch me reject nahi hota jab tak internet hi gayab na ho jaye ya CORS block na ho! Agar server 404 Not Found ya 500 Internal Error return karta hai, tab bhi fetch promise resolve hota hai. Isliye hamesha if (!response.ok) throw new Error(...) manually check karna padta hai!
10. Best Practices
- Dual await: Ek baar
await fetch()ke liye aur doosri baar stream read karne ke liyeawait response.json(). - Loading Indicator: Har asynchronous fetch me user ko visual spinner ya skeleton screen zaroor dikhayein.
- AbortController: User ke baar-baar type karne par puraane in-flight network requests cancel karne ke liye
AbortControllersignal use karein.
11. Try It Yourself
Playground me fetch('https://api.github.com/users/octocat').then(r => r.json()).then(console.log) likh kar GitHub ke public user profile ka JSON response dekhein.
12. Challenge
Ek Random Dog Image button banayein jo https://dog.ceo/api/breeds/image/random se image URL fetch karke screen par naya dog show kare.
13. Interview Questions
Answer: Pehla await fetch(url) HTTP response headers aate hi resolve ho jata hai (response object milta hai). Dusra await response.json() poori data body stream ko complete download aur parse karne ke baad resolve hota hai.
Answer: Cross-Origin Resource Sharing (CORS) browser ka security feature hai. Agar domain A (example.com) domain B (bank.com) ki API call karne ki koshish kare, toh browser use block kar deta hai jab tak bank ka server Access-Control-Allow-Origin header me permission na de.
14. Quick Revision
fetch()returns a Promise.- Check
response.okbefore parsing JSON. - POST requests need
method,headers, andJSON.stringify(body). - Always turn off spinners in the
finallyblock.
15. FAQ
Q1. Axios aur Fetch me kya farq hai?
Fetch browser me native hota hai (zero install). Axios ek external npm package hai jo auto JSON conversion aur 4xx/5xx status par automatic reject provide karta hai.
Q2. Fetch me headers kya hote hain?
Headers request ke meta-information hote hain, jaise authentication tokens (Authorization: Bearer token) aur data format (Content-Type: application/json).
Q3. Kya file upload Fetch se kar sakte hain?
Haan! FormData object bana kar fetch('/upload', { method: 'POST', body: formData }) use karein.
Q4. Request timeout kaise set karein?
AbortSignal.timeout(5000) ko fetch ke options me { signal: AbortSignal.timeout(5000) } ke taur par pass karein.
Q5. response.text() kab use karte hain?
Jab response JSON ke bajaye plain text, HTML ya CSV string me aa raha ho.
Fetch API, REST Requests, JSON & Loading States
1. Simple Definition
The Fetch API is the modern browser standard for performing asynchronous HTTP network requests (GET, POST, PUT, DELETE) to communicate with backend servers, cloud databases, and REST APIs to exchange data formatted as JSON (JavaScript Object Notation).
2. Real-Life Analogy
You (the Frontend Client) give your order to the Waiter (fetch request). The waiter walks back into the kitchen (the Backend API Server). While the chefs cook your meal, you continue chatting with your friends (non-blocking). When the food is prepared, the waiter returns with your steaming dish (JSON response)!
3. Complete GET Request Pattern with State Management
async function loadProducts() {
const statusEl = document.querySelector("#status");
const container = document.querySelector("#product-grid");
try {
// 1. Loading State
statusEl.textContent = "Loading catalog...";
statusEl.classList.remove("hidden");
// 2. Fetch network request
const res = await fetch("https://dummyjson.com/products?limit=6");
// Check for HTTP errors (404, 500)
if (!res.ok) throw new Error(`HTTP Error ${res.status}`);
const data = await res.json();
// 3. Empty State check
if (!data.products || data.products.length === 0) {
statusEl.textContent = "No products found.";
return;
}
// 4. Success State: Render items
statusEl.classList.add("hidden");
container.innerHTML = data.products.map(p => `
<div class="card">
<h3>${p.title}</h3>
<p>Price: $${p.price}</p>
</div>
`).join("");
} catch (error) {
// 5. Error State
statusEl.textContent = `Failed to load products: ${error.message}`;
statusEl.classList.add("text-error");
}
}
4. Sending Data: HTTP POST Request
async function createNewPost(postData) {
const response = await fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(postData)
});
const created = await response.json();
console.log("Created successfully with ID:", created.id);
}
5. Common Mistakes
A fundamental surprise for beginners: fetch() only rejects a Promise on complete network loss (e.g. offline). A 404 Not Found or 500 Server Error resolves successfully! You must explicitly check if (!response.ok)!
6. Best Practices
- Always design all 4 UI states: Loading, Success, Empty, and Error.
- Use
AbortControllerto cancel pending requests if a user navigates away. - Set request timeouts to prevent indefinite hanging on slow mobile networks.
7. Practice Exercise
Build a search input where typing a GitHub username fetches their public profile from https://api.github.com/users/{username} and displays avatar, bio, and repository counts.
8. Interview Questions
Answer: By instantiating an AbortController: pass controller.signal to the fetch options, and invoke controller.abort() whenever cancellation is required (e.g. during search autocomplete debouncing).
9. Summary / Cheat Card
fetch()initiates modern HTTP requests.- Always verify
response.okbefore callingresponse.json(). - Always handle all 4 UI states: Loading, Success, Empty, Error.
- Pass
method: "POST"andheaders: { "Content-Type": "application/json" }to send data.
10. FAQ
Q1. What is CORS?
CORS (Cross-Origin Resource Sharing) is a browser security mechanism that restricts web pages from requesting data from a different domain unless the destination server explicitly allows it via HTTP headers.