Lesson 9 • Intermediate

    Fetch API (Part 1)

    A deep dive into making HTTP requests, API architecture, JSON handling, security, CORS, streaming, authentication, pagination, rate limits, real-world examples, and more.

    What You'll Learn in This Lesson

    • Make GET, POST, PUT and DELETE requests
    • Parse JSON responses correctly
    • Handle errors and bad HTTP status codes
    • Send data with request headers and body
    • Understand CORS and how to deal with it
    • Implement retry logic and AbortController

    💡 Running Code Locally: While this online editor runs real JavaScript, some advanced examples may have limitations. For the best experience:

    • Download Node.js to run JavaScript on your computer
    • Use your browser's Developer Console (Press F12) to test code snippets
    • Create a .html file with <script> tags and open it in your browser

    📡 Real-World Analogy: The Fetch API is like ordering from a drive-thru:

    • • You send a request (speak into the microphone)
    • • You wait for a response (they prepare your order)
    • • You receive data (they hand you the bag)
    • • Sometimes things go wrong (they're out of fries) — you need error handling!

    🌐 Fetch API — The Backbone of Modern Web Applications

    The Fetch API is the heart of modern JavaScript development. Every interactive, data-driven website uses fetch() behind the scenes:

    HTTP MethodPurposeReal Example
    GETRetrieve dataLoading user profile
    POSTSend new dataCreating a new post
    PUT/PATCHUpdate dataEditing your bio
    DELETERemove dataDeleting a comment
    • TikTok for loading videos
    • YouTube for comments, videos, and metadata
    • Roblox for catalog items
    • Fortnite and GTA V stat tracking
    • Shopify for product details
    • Amazon for recommendations
    • Spotify for playlists
    • Instagram for posts, stories, reels
    • Trading platforms for live stock data

    Fetch is the engine connecting the browser (your JavaScript) to servers, databases, APIs, clouds, and backend systems around the world.

    If you understand fetch deeply, you can build:

    • ✔ web apps
    • ✔ dashboards
    • ✔ analytics tools
    • ✔ admin panels
    • ✔ full-stack apps
    • ✔ weather apps
    • ✔ stock trackers
    • ✔ game utilities
    • ✔ e-learning platforms
    • ✔ AI interfaces

    🚀 What Exactly Is the Fetch API?

    The Fetch API is a modern browser interface for making HTTP requests: GET, POST, PUT, DELETE, PATCH — everything.

    Before fetch(), developers used XMLHttpRequest (XHR). Fetch replaces ALL of it with a cleaner, Promise-based approach.

    Old (XHR)

    const req = new XMLHttpRequest();
    req.open("GET", "/api");
    req.onload = function() {
        console.log(req.responseText);
    };
    req.send();

    Modern (Fetch)

    const res = await fetch("/api");
    const data = await res.json();

    Cleaner. Faster. Easier. More powerful.

    📬 Basic GET Request — The Foundation

    const response = await fetch("https://api.example.com/data");
    const data = await response.json();
    console.log(data);

    But behind those 2 lines is a HUGE world:

    • status codes
    • redirects
    • CORS
    • headers
    • streaming
    • caching
    • authentication
    • JSON parsing
    • network errors
    • body handling
    • timeouts
    • abort controllers

    We will cover ALL of this in this mega lesson.

    🧠 Understanding the Fetch Response Object

    response contains:

    response.ok          // true/false if status is 200–299
    response.status      // e.g., 200, 404, 500
    response.statusText  // human readable text
    response.headers     // all server headers
    response.url         // final resolved URL
    response.redirected  // boolean
    response.type        // basic, cors, error, opaque
    response.body        // ReadableStream

    And methods:

    response.json()      // parse JSON
    response.text()      // raw text
    response.blob()      // files, images
    response.arrayBuffer() // binary
    response.formData()

    Fetch is far more than just .json().

    🧪 Full Syntax of fetch()

    fetch(url, {
        method: "GET",
        headers: { ... },
        body: "...",
        mode: "cors",
        cache: "no-cache",
        credentials: "include",
        redirect: "follow",
        referrerPolicy: "no-referrer"
    });

    We will break down each one deeply in this lesson.

    📡 Real Example — Fetching JSONPlaceholder API

    This free API is used in thousands of tutorials.

    const res = await fetch("https://jsonplaceholder.typicode.com/posts/1");
    const post = await res.json();
    console.log(post);

    Output:

    {
      "userId": 1,
      "id": 1,
      "title": "...",
      "body": "..."
    }

    🔥 Using Async/Await With Fetch (The Best Way)

    async function loadPost(id) {
        const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`);
        if (!res.ok) throw new Error("Failed to fetch post");
        return res.json();
    }
    
    const data = await loadPost(1);

    Async/await + fetch = modern JavaScript.

    🛑 Error Handling: Fetch Does NOT Throw on 400/500 Errors

    This surprises most developers.

    Fetch only throws on:

    • no internet
    • DNS failures
    • network disconnect
    • CORS issues

    But it DOES NOT throw on:

    • 404 Not Found
    • 500 Internal Server Error
    • 403 Forbidden

    So ALWAYS check:

    if (!res.ok) throw new Error(`HTTP ${res.status}`);

    🧨 Handling Failed JSON Parsing

    Server may return invalid JSON:

    try {
        const data = await res.json();
    } catch (err) {
        console.error("Bad JSON:", err);
    }

    This happens more often than beginners expect.

    📥 POST Requests — Sending Data

    Fetch makes POST simple:

    const res = await fetch("/api/users", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name: "Brayan", age: 16 })
    });

    📝 Common Fetch Methods

    GETRetrieve data
    POSTCreate new data
    PUT/PATCHUpdate existing data
    DELETERemove data

    📦 Sending FormData (No Need to JSON.stringify)

    const form = new FormData();
    form.append("file", fileInput.files[0]);
    
    fetch("/upload", {
        method: "POST",
        body: form
    });

    Used for:

    • photos
    • videos
    • profile pictures
    • documents

    This is how Instagram/TikTok upload images.

    🌍 CORS — The Gatekeeper of APIs

    CORS = Cross-Origin Resource Sharing
    One of the MOST misunderstood web concepts.

    Without CORS:

    Browser blocks request → API says: "You're not allowed."

    With CORS:

    API sends header:

    Access-Control-Allow-Origin: *

    Request allowed.

    CORS Modes in fetch:

    mode: "cors"        // default for most APIs
    mode: "no-cors"     // restricted, only opaque responses
    mode: "same-origin" // only internal requests

    🔐 Authorization Headers (Tokens, API Keys, JWT)

    Used in:

    • Fortnite API
    • GTA V stat API
    • YouTube API
    • Twitch API
    • Shopify API
    • Stripe API
    • Discord API
    fetch("/private", {
        headers: {
            "Authorization": "Bearer SECRET_TOKEN"
        }
    });

    🔄 PUT, PATCH, DELETE Requests

    PUT (Overwrite)

    fetch("/api/user/1", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name: "Boopie" })
    });

    PATCH (Partial Update)

    fetch("/api/user/1", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ age: 17 })
    });

    DELETE

    fetch("/api/user/1", {
        method: "DELETE"
    });

    ⚡ AbortController — Cancel Fetch Requests

    Imagine the user types fast into a search bar. You must cancel old requests:

    const controller = new AbortController();
    
    fetch("/search?q=hello", {
        signal: controller.signal
    });
    
    // Cancel
    controller.abort();

    Used in:

    • live search
    • auto-complete
    • dashboard filtering

    📊 Fetching Large Lists with Pagination

    Real APIs paginate:

    /posts?limit=10&page=2

    Fetch example:

    async function loadPage(page) {
        const res = await fetch(`/posts?page=${page}&limit=10`);
        const data = await res.json();
        return data;
    }

    Used in every real platform:

    • TikTok
    • Instagram
    • YouTube
    • Reddit
    • Twitter
    • Amazon

    📡 Parallel Fetching With Promise.all()

    const [user, posts, comments] = await Promise.all([
        fetch("/user/1").then(r => r.json()),
        fetch("/posts").then(r => r.json()),
        fetch("/comments").then(r => r.json())
    ]);

    This is how dashboards load instantly.

    🔥 Real Example: Loading a Dashboard

    async function loadDashboard() {
        const [
            stats,
            notifications,
            recent
        ] = await Promise.all([
            fetch("/dashboard/stats").then(r => r.json()),
            fetch("/dashboard/notifications").then(r => r.json()),
            fetch("/dashboard/recent").then(r => r.json())
        ]);
    
        return { stats, notifications, recent };
    }

    Perfect for:

    • analytics
    • admin panels
    • personal accounts

    🌐 GET Request with Query Parameters

    const url = new URL("https://api.example.com/search");
    url.searchParams.set("q", "javascript");
    url.searchParams.set("limit", 20);
    
    const res = await fetch(url);

    Easier and cleaner than string concatenation.

    🌐 Understanding HTTP Status Codes

    Fetch won't throw errors automatically, so YOU must check status codes manually.

    🟢 Success Codes

    • 200 OK
    • 201 Created
    • 204 No Content

    🔐 Authentication Errors

    • 401 Unauthorized
    • 403 Forbidden

    🔴 Client Errors

    • 404 Not Found
    • 429 Too Many Requests → API rate-limiting (very common)

    🔥 Server Errors

    • 500 Internal Server Error
    • 502 Bad Gateway
    • 503 Service Unavailable
    • 504 Gateway Timeout

    Mastering status codes = mastering error handling.

    🎯 Fetch with Retry Logic

    Real APIs sometimes fail. So you need retry strategies.

    async function retryFetch(url, attempts = 3) {
        for (let i = 0; i < attempts; i++) {
            try {
                const res = await fetch(url);
                if (!res.ok) throw new Error();
                return res.json();
            } catch (err) {
                if (i === attempts - 1) throw err;
                await new Promise(r => setTimeout(r, 500));
            }
        }
    }

    Used by:

    • Stripe
    • AWS
    • Google Cloud
    • TikTok API
    • GitHub API

    🧠 Real-World Example: Authenticate User & Get Profile

    async function getProfile() {
        const token = localStorage.getItem("token");
    
        const res = await fetch("/user", {
            headers: {
                "Authorization": `Bearer ${token}`
            }
        });
    
        if (!res.ok) throw new Error("Not authorized");
    
        return res.json();
    }

    This is how dashboards like Facebook, YouTube Studio, Amazon Seller Central, and TikTok Business load your data securely.

    🛡️ Security Best Practices

    • ❌ Never expose API keys:
      fetch(`https://api.example.com?key=SECRET`)

      Anyone can inspect this.

    • ❌ Never use private APIs from frontend - Everything must go through your backend.
    • ✔️ Always sanitize user input - Attackers can inject script tags.
    • ✔️ Always validate server responses - Servers can get hacked or misconfigured.

    Fetch API Practice

    Learn to fetch data from APIs and handle responses!

    Try it Yourself »
    JavaScript
    // Practice Fetch API (simulated)
    // Note: Real fetch requires a browser environment
    
    // Simulated fetch response
    const mockPosts = [
        { id: 1, title: "Getting Started with JavaScript" },
        { id: 2, title: "Understanding Async/Await" },
        { id: 3, title: "Mastering the Fetch API" }
    ];
    
    async function fetchPosts() {
        try {
            console.log("Fetching posts...");
            
            // Simulate network delay
            await new Promise(resolve => setTimeout(resolve, 500));
            
            
    ...

    🎯 Practice Challenge

    Try these tasks:

    1. 1️⃣ Fetch data from a public API and display it
    2. 2️⃣ Create a POST request to send data to an API
    3. 3️⃣ Add error handling for failed requests
    4. 4️⃣ Implement retry logic for failed requests
    5. 5️⃣ Use Promise.all() to fetch multiple resources in parallel
    6. 6️⃣ Add authentication headers to a request
    7. 7️⃣ Handle different HTTP status codes appropriately

    🏁 Recap

    You learned:

    • ✅ Basics of the Fetch API
    • ✅ Understanding Response objects
    • ✅ GET, POST, PUT, PATCH, DELETE requests
    • ✅ Error handling and status codes
    • ✅ CORS and how it works
    • ✅ Authentication with headers
    • ✅ Pagination and parallel fetching
    • ✅ AbortController for canceling requests
    • ✅ Retry logic for failed requests
    • ✅ Security best practices

    The Fetch API is the foundation of modern web communication. Once you master it, you can build any data-driven application with confidence.

    📋 Quick Reference — Fetch API

    ActionCode Snippet
    Basic GETconst res = await fetch(url);
    Get JSONconst data = await res.json();
    Check Successif (!res.ok) throw new Error();
    POST JSONfetch(url, { method: 'POST', body: ... })
    Headersheaders: { 'Content-Type': 'application/json' }

    Lesson 9 Complete — Fetch API!

    You can now connect your JavaScript code to the outside world — fetching data, sending forms, and building real dynamic applications.

    Up next: Error Handling — making your applications crash-proof and professional! 🛡️

    Sign up for free to track which lessons you've completed and get learning reminders.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy PolicyTerms of Service