Fetch API

Back

Loading concept...

📬 The Fetch API: Your Browser’s Magical Messenger


🎭 Once Upon a Web Request…

Imagine you’re at home and you want a pizza. You can’t teleport to the pizza shop, right? So what do you do? You send a messenger — maybe you call them, or use an app. That messenger goes to the shop, tells them what you want, waits for the pizza, and brings it back to you.

The Fetch API is your browser’s messenger. It goes out to the internet, asks for things (data, images, information), and brings them back to your web page. Simple as that!


🚀 The fetch() Function: Your One-Stop Request Maker

The fetch() function is like picking up the phone to call the pizza shop. You tell it where to go (the URL), and it starts the journey.

The Simplest Fetch

fetch('https://api.example.com/pizzas')
  .then(response => response.json())
  .then(data => console.log(data));

What just happened?

  1. 📞 We called fetch() with a URL
  2. ⏳ It went to that address
  3. 📦 It brought back a response
  4. 🍕 We unpacked the data!

Key Insight đź’ˇ

fetch() returns a Promise — a pinky promise that says “I’ll get back to you with the answer!”


⚙️ Request Options: Customizing Your Order

Sometimes you need more than just “get me a pizza.” You want to specify toppings, delivery time, or special instructions. That’s what request options are for!

fetch('https://api.example.com/order', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    pizza: 'Margherita',
    size: 'large'
  })
});

Common Options You’ll Use

Option What It Does Example
method How to send (GET, POST, etc.) 'POST'
headers Extra info for the server {'Content-Type': 'application/json'}
body Data to send JSON.stringify({...})
mode Security rules 'cors'
credentials Send cookies? 'include'

đź“‹ Request Headers: The Envelope Information

When you send a letter, the envelope has important info: who it’s from, who it’s to, if it needs special handling. Headers work the same way!

fetch('https://api.example.com/data', {
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer my-secret-token',
    'Accept': 'application/json'
  }
});

Common Headers Explained

Header Purpose Like…
Content-Type What format is the data? “This box contains fragile glass”
Authorization Prove who you are Your ID badge
Accept What format do you want back? “Reply in English please”
User-Agent What’s making the request? Your return address

🎯 HTTP Methods: The Action Words

Just like verbs in a sentence, HTTP methods tell the server what action you want to take.

graph TD A["HTTP Methods"] --> B["GET"] A --> C["POST"] A --> D["PUT"] A --> E["DELETE"] A --> F["PATCH"] B --> B1["📖 Read data"] C --> C1["✨ Create new"] D --> D1["🔄 Replace all"] E --> E1["🗑️ Remove"] F --> F1["✏️ Update part"]

Quick Examples

GET — Fetch data (default method):

fetch('https://api.example.com/users');

POST — Create something new:

fetch('https://api.example.com/users', {
  method: 'POST',
  body: JSON.stringify({ name: 'Alex' })
});

DELETE — Remove something:

fetch('https://api.example.com/users/5', {
  method: 'DELETE'
});

📦 Response Object: The Delivery Package

When your messenger returns, they don’t just hand you pizza — they bring a whole package with info: “Here’s your pizza, it cost $15, it’s still hot, here’s the receipt.”

The Response object contains:

fetch('https://api.example.com/data')
  .then(response => {
    console.log(response.ok);      // true if successful
    console.log(response.status);  // 200, 404, 500, etc.
    console.log(response.headers); // More info
    console.log(response.url);     // Where we went
  });

Response Properties at a Glance

Property What It Tells You
ok Was it successful? (true/false)
status Number code (200 = good, 404 = not found)
statusText Human-readable status
headers Extra response info
url Final URL after redirects

🔓 Response Methods: Unpacking Your Delivery

The response is like a wrapped present. You need to unwrap it to see what’s inside!

graph TD R["Response"] --> J[".json#40;#41;"] R --> T[".text#40;#41;"] R --> B[".blob#40;#41;"] R --> F[".formData#40;#41;"] R --> A[".arrayBuffer#40;#41;"] J --> J1["📊 For JSON data"] T --> T1["📝 For plain text"] B --> B1["🖼️ For images/files"] F --> F1["📋 For form data"] A --> A1["💾 For binary data"]

Most Common: JSON and Text

Getting JSON data:

fetch('https://api.example.com/users')
  .then(response => response.json())
  .then(users => {
    console.log(users);
  });

Getting plain text:

fetch('https://example.com/page.html')
  .then(response => response.text())
  .then(html => {
    console.log(html);
  });

⚠️ Important Rule!

You can only read the response body once. If you call .json(), you can’t then call .text() on the same response!


🛡️ Fetch Error Handling: When Things Go Wrong

Here’s a surprise: fetch() doesn’t throw an error for 404 or 500 responses! It only fails if the network itself fails.

The Wrong Way ❌

fetch('https://api.example.com/missing')
  .then(data => console.log(data))
  .catch(err => console.log(err));
// This won't catch a 404!

The Right Way âś…

fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => {
    console.log('Something went wrong:', error);
  });

Using Async/Await (Cleaner!)

async function getData() {
  try {
    const response = await fetch('https://api.example.com/data');

    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.log('Oops!', error);
  }
}

âś‹ Aborting Requests: The Emergency Stop Button

Imagine your messenger is halfway to the pizza shop, but you change your mind. You need to call them back!

The AbortController lets you cancel requests that haven’t finished yet.

How It Works

graph LR A["Create AbortController"] --> B["Get signal"] B --> C["Pass signal to fetch"] C --> D{Need to cancel?} D -->|Yes| E["Call abort"] D -->|No| F["Request completes"] E --> G["Request canceled!"]

Real Example

// 1. Create the controller
const controller = new AbortController();

// 2. Start the fetch with the signal
fetch('https://api.example.com/bigdata', {
  signal: controller.signal
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => {
    if (error.name === 'AbortError') {
      console.log('Request was canceled!');
    }
  });

// 3. Cancel anytime!
controller.abort();

Timeout Example

async function fetchWithTimeout(url, timeout = 5000) {
  const controller = new AbortController();

  const timeoutId = setTimeout(() => {
    controller.abort();
  }, timeout);

  try {
    const response = await fetch(url, {
      signal: controller.signal
    });
    clearTimeout(timeoutId);
    return response;
  } catch (error) {
    clearTimeout(timeoutId);
    throw error;
  }
}

🎓 Putting It All Together

Here’s a complete, real-world example using everything we learned:

async function fetchUserData(userId) {
  const controller = new AbortController();

  // Auto-cancel after 10 seconds
  const timeout = setTimeout(() => {
    controller.abort();
  }, 10000);

  try {
    const response = await fetch(
      `https://api.example.com/users/${userId}`,
      {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer token123'
        },
        signal: controller.signal
      }
    );

    clearTimeout(timeout);

    if (!response.ok) {
      throw new Error(`Failed: ${response.status}`);
    }

    const user = await response.json();
    return user;

  } catch (error) {
    clearTimeout(timeout);

    if (error.name === 'AbortError') {
      console.log('Request timed out');
    } else {
      console.log('Error:', error.message);
    }
    return null;
  }
}

🏆 Summary: Your Fetch API Toolkit

Concept What to Remember
fetch() Start a request, returns a Promise
Request Options Customize with method, headers, body
Headers Extra info like Content-Type, Authorization
HTTP Methods GET=read, POST=create, PUT=replace, DELETE=remove
Response Object Contains ok, status, headers
Response Methods .json(), .text(), .blob() to read body
Error Handling Check response.ok, use try/catch
AbortController Cancel requests with .abort()

🚀 You’re Ready!

You now know how to:

  • âś… Make basic and advanced fetch requests
  • âś… Send data with different HTTP methods
  • âś… Handle responses and errors properly
  • âś… Cancel requests when needed

The Fetch API is your gateway to connecting with the entire internet. Go build something amazing! 🌟

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.