šŸš€ API Integration Masterclass

Day 22-24: Complete Guide with Interactive Demos

šŸ“š API Integration Kya Hai?

API (Application Programming Interface): A set of rules and protocols that allows different software applications to communicate with each other.

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

Fetch API: A modern, promise-based JavaScript API for making HTTP requests to servers. It provides a cleaner and more powerful way to make network requests compared to older methods like XMLHttpRequest.

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

Output yahan dikhega...

POST Request: Server ko naya data bhejne ke liye

Output yahan dikhega...

Error Handling: Jab API fail ho jaye

Output yahan dikhega...
// Basic Fetch Syntax fetch('https://api.example.com/data') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); // With async/await (Modern approach) async function fetchData() { try { const response = await fetch('https://api.example.com/data'); const data = await response.json(); console.log(data); } catch (error) { console.error('Error:', error); } }

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

Output yahan dikhega...

3ļøāƒ£ Loading States & Skeleton UI

Loading State: A visual indicator that shows the user that content is being fetched or processed, improving user experience by providing feedback during asynchronous operations.

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

// Loading State Implementation async function fetchWithLoading() { const loadingEl = document.getElementById('loading'); loadingEl.style.display = 'block'; // Show loading try { const response = await fetch('https://api.example.com/data'); const data = await response.json(); // Process data } catch (error) { console.error(error); } finally { loadingEl.style.display = 'none'; // Hide loading } }

4ļøāƒ£ Error Handling & Retry Patterns

Error Handling: The process of anticipating, detecting, and resolving errors that occur during API calls, ensuring the application remains stable and provides meaningful feedback to users.

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

Output yahan dikhega...
0%
// Retry Pattern Implementation async function fetchWithRetry(url, options = {}, retries = 3) { for (let i = 0; i < retries; i++) { try { const response = await fetch(url, options); if (!response.ok) throw new Error(`HTTP ${response.status}`); return await response.json(); } catch (error) { if (i === retries - 1) throw error; console.log(`Retry ${i + 1}/${retries}...`); await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1))); } } }

5ļøāƒ£ AbortController - Request Cancel Karna

AbortController: A Web API that allows you to abort one or more fetch requests programmatically, useful for canceling ongoing requests when they're no longer needed.

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

Output yahan dikhega...
// AbortController Usage const controller = new AbortController(); const signal = controller.signal; fetch('https://api.example.com/data', { signal }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => { if (error.name === 'AbortError') { console.log('Request cancelled!'); } }); // Cancel the request controller.abort();

6ļøāƒ£ Debounced API Search

Debouncing: A programming technique that delays the execution of a function until after a certain amount of time has passed since it was last called, reducing the number of times a function is executed.

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

Results yahan dikhenge...
// Debounce Function function debounce(func, delay) { let timeoutId; return function(...args) { clearTimeout(timeoutId); timeoutId = setTimeout(() => func.apply(this, args), delay); }; } // Usage const searchAPI = debounce(async (query) => { const response = await fetch(`/api/search?q=${query}`); const data = await response.json(); displayResults(data); }, 500); input.addEventListener('input', (e) => searchAPI(e.target.value));

7ļøāƒ£ Multiple API Calls Handle Karna

Promise.all(): A method that takes an array of promises and returns a single promise that resolves when all input promises have resolved, or rejects if any promise rejects.

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

Output yahan dikhega...
// Sequential (One after another) const user = await fetch('/api/user/1').then(r => r.json()); const posts = await fetch('/api/posts/1').then(r => r.json()); const comments = await fetch('/api/comments/1').then(r => r.json()); // Parallel (All at once - FASTER!) const [user, posts, comments] = await Promise.all([ fetch('/api/user/1').then(r => r.json()), fetch('/api/posts/1').then(r => r.json()), fetch('/api/comments/1').then(r => r.json()) ]); // Race (First one wins) const fastest = await Promise.race([ fetch('/api/server1/data'), fetch('/api/server2/data'), fetch('/api/server3/data') ]);

8ļøāƒ£ Real-time Updates & Polling

Polling: A technique where the client repeatedly requests data from the server at regular intervals to check for updates, simulating real-time behavior.

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

Polling start karo...
Poll Count: 0
// Simple Polling Implementation let pollingInterval; function startPolling(url, interval = 3000) { pollingInterval = setInterval(async () => { try { const response = await fetch(url); const data = await response.json(); updateUI(data); } catch (error) { console.error('Polling error:', error); } }, interval); } function stopPolling() { clearInterval(pollingInterval); }

šŸŽÆ 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