Curriculum / Advanced / Lesson 23

Fetch API

Making HTTP requests and handling responses.

23 of 30
advanced 📖 7 min read 🎯 4 questions

What is the Fetch API?

The Fetch API provides a modern way to make HTTP requests in JavaScript. It's built on Promises and replaces older methods like XMLHttpRequest.

💡 Key insight fetch() returns a Promise that resolves to a Response object. You need to call .json() or .text() to get the actual data.

Basic GET Request

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

With Async/Await

async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');
    if (!response.ok) throw new Error('Network response was not ok');
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Error:', error);
  }
}

POST Request

const response = await fetch('https://api.example.com/data', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ name: 'Alice', age: 25 })
});

Handling Different Response Types

Common Mistakes

Quick Quiz

1. What does fetch() return?

2. How do you check if a fetch request was successful?

3. Which method parses the response as JSON?

4. What header must you set for a POST request with JSON data?

Summary

Back to curriculum