🌐

How to Use Fetch API in JavaScript

JavaScriptIntermediate

Make HTTP requests with the Fetch API.

Code Example

JavaScript
// Basic GET request
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.error("Error:", error));

// Async/await version
async function fetchData() {
  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.error("Error:", error);
  }
}

// POST request
async function postData() {
  const response = await fetch("https://api.example.com/users", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      name: "Alice",
      email: "alice@example.com"
    })
  });
  return response.json();
}

// PUT request
async function updateUser(id, data) {
  const response = await fetch(`https://api.example.com/users/${id}`, {
    method: "PUT",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(data)
  });
  return response.json();
}

// DELETE request
async function deleteUser(id) {
  await fetch(`https://api.example.com/users/${id}`, {
    method: "DELETE"
  });
}

// Request with headers
async function fetchWithAuth() {
  const token = localStorage.getItem("token");
  const response = await fetch("https://api.example.com/protected", {
    headers: {
      "Authorization": `Bearer ${token}`,
      "Content-Type": "application/json"
    }
  });
  return response.json();
}

// Handle different response types
async function fetchText() {
  const response = await fetch("https://example.com/file.txt");
  return response.text();
}

async function fetchBlob() {
  const response = await fetch("https://example.com/image.png");
  return response.blob();
}

// Abort request
const controller = new AbortController();
setTimeout(() => controller.abort(), 5000);

fetch("https://api.example.com/slow", {
  signal: controller.signal
}).catch(error => {
  if (error.name === "AbortError") {
    console.log("Request aborted");
  }
});

Explanation

Fetch returns a Promise. Use .then() or async/await. Check response.ok for errors. Use method, headers, body for POST/PUT. AbortController for cancellation.

Related Tutorials