learn2kode.in

What Is the Fetch API in JavaScript?

The JavaScript Fetch API is a modern Web API used to make HTTP requests such as GET, POST, PUT, and DELETE from the browser. It allows JavaScript applications to communicate with servers, fetch data from APIs, and update web pages dynamically without reloading the page. If you are learning JavaScript Fetch API tutorial for beginners, this topic is essential before moving to frameworks like React, Vue, or Angular, as Fetch is widely used for API calls.
Why Use the Fetch API?

The Fetch API is designed to replace older techniques like XMLHttpRequest with a cleaner, promise-based syntax. Key Benefits:

Basic Syntax of Fetch API

fetch(url)
  .then(response => response.json())
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error("Error:", error);
  });
Explanation
Example: Fetching Data from an API
fetch("https://jsonplaceholder.typicode.com/posts")
  .then(response => response.json())
  .then(posts => {
    console.log(posts);
  })
  .catch(error => console.error(error));
Using Fetch API with async/await

This is the recommended modern approach.

async function getPosts() {
  try {
    const response = await fetch("https://jsonplaceholder.typicode.com/posts");
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error("Error:", error);
  }
}

getPosts();
Making a POST Request with Fetch API
fetch("https://jsonplaceholder.typicode.com/posts", {
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    title: "Learn Fetch API",
    body: "Fetch API tutorial for beginners",
    userId: 1
  })
})
.then(response => response.json())
.then(data => console.log(data));
Handling Errors in Fetch API
Fetch does not fail on HTTP errors (404, 500). You must handle them manually.
fetch("https://api.example.com/data")
  .then(response => {
    if (!response.ok) {
      throw new Error("Network response was not ok");
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error(error));

Common Use Cases of Fetch API

This makes Fetch API a core skill for frontend and full-stack developers.

Fetch API vs Axios