🌐 Fetch API in JavaScript – Complete Tutorial

The Fetch API is a modern JavaScript API used to make HTTP requests and communicate with servers. It returns aPromise, making it easy to work with asynchronous operations using.then() or async/await.

📌 What is the Fetch API?

The Fetch API is a built-in browser interface for sending network requests and receiving responses. It supports all common HTTP methods such asGET, POST, PUT,PATCH, and DELETE.

>>"Fetch provides a simple, flexible, and promise-based way to communicate with web servers."

💡 Why Use the Fetch API?

  • 🌍 Retrieve data from APIs
  • 📤 Send data to a server
  • ⚡ Promise-based asynchronous programming
  • 📦 Built into modern browsers (no external library required)
  • 🔄 Supports JSON, text, blobs, files, and more

🛠 Basic Syntax

Fetch Syntax

fetch(url, options)
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

📥 GET Request

By default, fetch() performs a GET request.

GET Request

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

📤 POST Request

Use the POST method to send data to the server.

POST Request

fetch("https://api.example.com/users", {
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    name: "John",
    age: 25
  })
})
.then(response => response.json())
.then(data => console.log(data));

✏️ PUT Request

Use PUT to replace an existing resource.

PUT Request

fetch("https://api.example.com/users/1", {
  method: "PUT",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    name: "Alice"
  })
});

🩹 PATCH Request

Use PATCH to partially update a resource.

PATCH Request

fetch("https://api.example.com/users/1", {
  method: "PATCH",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    age: 30
  })
});

🗑 DELETE Request

DELETE Request

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

📊 Response Object

Property / MethodDescription
oktrue if the response status is 200–299.
statusHTTP status code.
statusTextStatus message.
headersResponse headers.
json()Reads the response body as JSON.
text()Reads the response body as plain text.
blob()Reads the response as a Blob.
arrayBuffer()Reads the response as an ArrayBuffer.

📄 Reading JSON

Read JSON

fetch("/users")
  .then(response => response.json())
  .then(data => {
    console.log(data);
  });

📃 Reading Text

Read Text

fetch("/message.txt")
  .then(response => response.text())
  .then(text => {
    console.log(text);
  });

🖼 Reading Images

Read Blob

fetch("/image.png")
  .then(response => response.blob())
  .then(blob => {
    console.log(blob);
  });

⚡ Using async/await

The async/await syntax makes asynchronous code easier to read.

async/await Example

async function loadUsers() {
  try {
    const response = await fetch(
      "https://api.example.com/users"
    );

    const data =
      await response.json();

    console.log(data);

  } catch (error) {
    console.error(error);
  }
}

loadUsers();

❌ Handling Errors

A network failure rejects the promise, but HTTP errors like404 or 500 do not. Checkresponse.ok manually.

Check HTTP Errors

fetch("/users")
  .then(response => {

    if (!response.ok) {
      throw new Error("Request failed");
    }

    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error(error));

🛠 Complete Example

Load User Data

async function getUser() {

  try {

    const response = await fetch(
      "https://api.example.com/user/1"
    );

    if (!response.ok) {
      throw new Error("HTTP Error");
    }

    const user =
      await response.json();

    console.log(user);

  } catch (error) {
    console.error(error);
  }

}

getUser();

📊 Fetch API vs XMLHttpRequest

FeatureFetch APIXMLHttpRequest
Promise-Based✅ Yes❌ No
async/await Support✅ Yes❌ No
Simpler Syntax✅ Yes⚠️ More Verbose
Built Into Browsers✅ Yes✅ Yes

⚠️ Common Mistakes

  • ❌ Forgetting to return response.json().
  • ❌ Assuming fetch() rejects on HTTP 404 or 500 responses.
  • ❌ Forgetting to convert request bodies with JSON.stringify() when sending JSON.
  • ❌ Omitting the Content-Type header for JSON requests.

Note

fetch() returns a Promise that resolves as soon as the server responds with headers. Reading the response body using methods likejson() or text() is a separate asynchronous step.

✅ Best Practices

  • ⚡ Prefer async/await for cleaner asynchronous code.
  • ✅ Check response.ok before processing the response.
  • 🧩 Use try...catch to handle network errors with async/await.
  • 📦 Send JSON using JSON.stringify() and the appropriate Content-Type header.
  • 🔒 Avoid exposing sensitive information such as API keys in client-side code.

🎯 Summary

The Fetch API is the modern standard for making HTTP requests in JavaScript. Its promise-based design, support for async/await, and flexible request and response handling make it the preferred choice for communicating with REST APIs and other web services.