Fetch API

Introduction

The Fetch API is a modern JavaScript feature used to make network requests to servers. It allows developers to retrieve and send data asynchronously without reloading the web page. Fetch is widely used for working with APIs and handling dynamic data in web applications.

Core Purpose of Fetch API

The Fetch API helps developers communicate with servers by sending requests and receiving responses. It is mainly used to load data from external sources such as databases or third party APIs and display it on a website in real time.

How Fetch API Works

Fetch uses promises to handle asynchronous operations. When a request is sent, it returns a promise that resolves once the response is received. This makes it easier to manage data and avoid blocking the user interface.

Basic Syntax Example

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

Making Different Types of Requests

GET Request
Used to retrieve data from a server

fetch("https://api.example.com/users")
.then(res => res.json())
.then(data => console.log(data));

POST Request
Used to send data to a server

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

PUT Request
Used to update existing data

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

DELETE Request
Used to remove data

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

Handling Errors

Error handling is important when working with APIs. Fetch only rejects a promise on network failure, so developers must manually check response status.

fetch("https://api.example.com/data")
.then(response => {
if (!response.ok) {
throw new Error("Request failed");
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.log(error));

Advantages of Fetch API

Simple and clean syntax
Built into modern browsers
Uses promises for better readability
Supports asynchronous programming
Flexible for different request types

Conclusion

The Fetch API is an essential tool in modern web development. It allows developers to interact with servers efficiently and build dynamic applications that update data in real time. Learning Fetch API improves your ability to work with APIs and create responsive web experiences.

Home » Advanced JavaScript > Asynchronous JavaScript > Fetch API