š API Integration Kya Hai?
Simple shabdon mein: API ek waiter ki tarah hai jo aapke order (request) ko kitchen (server) tak le jaata hai aur phir khana (response) wapas laata hai. Jaise aap restaurant mein directly kitchen mein nahi jaate, waise hi aapka application directly database ya server se baat nahi karta - API ke through karta hai!
š„ļø Client
Your App
š API
Middleware
š¾ Server
Database
1ļøā£ Fetch API
Samjho aise: Fetch API JavaScript ka built-in tarika hai server se data mangne ka. Ye promises use karta hai, matlab asynchronous hai - aapka code wait nahi karta, baaki kaam karta rehta hai jab tak response nahi aata.
šÆ Live Demo: Fetch API
GET Request: Server se data fetch karne ke liye
POST Request: Server ko naya data bhejne ke liye
Error Handling: Jab API fail ho jaye
2ļøā£ HTTP Methods (CRUD Operations)
Ye 4 main methods hain: GET (data lao), POST (naya data banao), PUT (data update karo), DELETE (data hatao). Isko CRUD operations bhi kehte hain - Create, Read, Update, Delete.
š„ GET
Purpose: Retrieve data
Server se data fetch karta hai
Read Onlyš¤ POST
Purpose: Create new data
Naya data server pe bhejta hai
Creates Newāļø PUT
Purpose: Update existing data
Purane data ko update karta hai
Modifiesšļø DELETE
Purpose: Remove data
Data ko delete karta hai
RemovesšÆ Live Demo: All HTTP Methods
3ļøā£ Loading States & Skeleton UI
Kyun zaroori hai? Jab API call hoti hai, user ko pata hona chahiye ki kuch ho raha hai. Loading state dikhane se user experience better hota hai. Skeleton UI ek modern approach hai jahan actual content ki shape dikhate hain loading ke time.
šÆ Live Demo: Loading States
4ļøā£ Error Handling & Retry Patterns
Real life mein: API calls kabhi kabhi fail ho sakti hain - network issue, server down, wrong URL, etc. Achhe developer hamesha error handling karte hain. Retry pattern matlab agar ek baar fail ho jaye toh automatically dobara try karo.
šÆ Live Demo: Retry Pattern
Ye demo 3 baar try karega agar API fail ho jaye
5ļøā£ AbortController - Request Cancel Karna
Use case: Maan lo user ne search kiya, API call start hui, lekin user ne turant search term change kar diya. Ab purani API call ki zaroorat nahi hai. AbortController se hum usko cancel kar sakte hain. Ye performance improve karta hai aur unnecessary requests bachata hai.
šÆ Live Demo: AbortController
Start a long request and cancel it before completion
6ļøā£ Debounced API Search
Problem: Agar user search box mein type kar raha hai, har keystroke pe API call karoge toh bahut saari unnecessary calls ho jayengi. Solution: Debouncing - user typing khatam karne ke baad (jaise 500ms wait karke) API call karo. Ye bandwidth bachata hai aur performance improve karta hai.
šÆ Live Demo: Debounced Search
Type karo aur dekho - API call 500ms ke baad hogi
7ļøā£ Multiple API Calls Handle Karna
Scenario: Kabhi kabhi aapko ek saath multiple APIs call karni padti hain. Teen tarike hain: Sequential (ek ke baad ek), Parallel (sab ek saath), aur Race (jo pehle aaye usko use karo). Promise.all() sabse common hai parallel calls ke liye.
šÆ Live Demo: Multiple API Calls
8ļøā£ Real-time Updates & Polling
Kab use karein? Jab aapko real-time updates chahiye ho - jaise stock prices, notifications, live scores. Polling matlab har kuch seconds mein API call karke check karo ki koi naya data hai ya nahi. Dhyan rahe - zyada frequent polling server pe load badha sakti hai!
šÆ Live Demo: Polling
Har 3 seconds mein random data fetch hoga
šÆ Interview Questions (Basic to Advanced)
Click on each question to reveal the answer
Q1. Fetch API aur XMLHttpRequest mein kya difference hai? (Basic)
Answer:
- Fetch API: Modern, promise-based, cleaner syntax, returns Response object
- XMLHttpRequest: Older, callback-based, more verbose, complex error handling
- Key Difference: Fetch doesn't reject on HTTP errors (404, 500) - you need to check response.ok
- Hinglish: Fetch modern hai aur use karna easy hai. XMLHttpRequest purana tarika hai jo callbacks use karta tha.
Q2. CORS error kya hai aur kaise solve karein? (Intermediate)
Answer:
- CORS (Cross-Origin Resource Sharing): Browser security feature that blocks requests to different domains
- Error: "Access to fetch has been blocked by CORS policy"
- Solutions:
- Backend pe CORS headers enable karo (Access-Control-Allow-Origin)
- Proxy server use karo (development mein)
- JSONP use karo (old method, not recommended)
- Hinglish: CORS ek security feature hai. Agar aap different domain se API call kar rahe ho toh server ko explicitly allow karna padta hai.
Q3. Debouncing aur Throttling mein kya fark hai? (Intermediate)
Answer:
- Debouncing: Function execute hota hai jab user action stop kar de (after delay)
Example: Search box - user typing band kare tab API call - Throttling: Function execute hota hai at regular intervals, chahe user action continue ho
Example: Scroll event - har 200ms mein ek baar execute - Hinglish: Debouncing = "Ruk jao, phir karo", Throttling = "Thoda thoda karke karo"
Q4. Promise.all() aur Promise.race() mein difference explain karo with use cases (Advanced)
Answer:
- Promise.all():
- Waits for ALL promises to resolve
- Agar ek bhi fail ho toh pura fail
- Use case: Jab sabhi data chahiye ho (user + posts + comments)
- Promise.race():
- Returns jab FIRST promise resolve/reject ho
- Baaki promises ignore ho jate hain
- Use case: Multiple servers se fastest response chahiye, timeout implementation
- Promise.allSettled(): Sabka wait karta hai, failures ko bhi handle karta hai (bonus!)
Q5. API retry logic implement karte waqt exponential backoff kyun use karte hain? (Advanced)
Answer:
- Exponential Backoff: Har retry ke baad wait time exponentially increase hota hai (1s, 2s, 4s, 8s...)
- Why?
- Server ko recover hone ka time milta hai
- Network congestion kam hota hai
- Prevents "thundering herd" problem
- Formula: delay = baseDelay * (2 ^ attemptNumber)
- Hinglish: Agar server down hai toh turant dobara request bhejne se aur problem hogi. Thoda wait karo, phir try karo. Har baar wait time badhao.
Q6. AbortController ka real-world use case explain karo (Advanced)
Answer:
- Use Cases:
- Search Autocomplete: User typing ke time purani requests cancel karo
- Component Unmount: React/Vue mein component unmount hone pe pending requests cancel karo (memory leak prevention)
- Timeout Implementation: Agar API 5 seconds mein respond nahi kare toh cancel karo
- User Navigation: User dusre page pe chala gaya toh current page ki requests cancel karo
- Code Example:
const controller = new AbortController(); setTimeout(() => controller.abort(), 5000); // 5s timeout fetch(url, { signal: controller.signal }) .catch(err => { if (err.name === 'AbortError') { console.log('Request timeout!'); } });
Q7. Polling vs WebSockets vs Server-Sent Events - kab kya use karein? (Expert)
Answer:
- Polling:
- Simple implementation, works everywhere
- Use: Jab updates frequently nahi chahiye (every 30s+)
- Cons: Inefficient, server load zyada
- WebSockets:
- Full-duplex, bidirectional communication
- Use: Chat apps, multiplayer games, collaborative editing
- Cons: Complex setup, requires WebSocket server
- Server-Sent Events (SSE):
- One-way communication (server to client)
- Use: Live feeds, notifications, stock tickers
- Cons: Only server can push, not bidirectional
- Decision Tree:
- Need bidirectional? ā WebSockets
- Only server pushes? ā SSE
- Simple updates? ā Polling
š Quick Summary
- ā Fetch API: Modern way to make HTTP requests
- ā HTTP Methods: GET, POST, PUT, DELETE for CRUD operations
- ā Error Handling: Always use try-catch and retry patterns
- ā Loading States: Better UX with spinners and skeleton UI
- ā AbortController: Cancel unnecessary requests
- ā Debouncing: Optimize search and input events
- ā Multiple Calls: Use Promise.all() for parallel execution
- ā Polling: Regular intervals for real-time updates