DEV Community

Cover image for Fetch API in JavaScript
ABISHEK M
ABISHEK M

Posted on

Fetch API in JavaScript

The Fetch API is a built-in feature in JavaScript that is used to communicate with a server or an API. It helps us send requests to a server and receive data from it. Fetch API is commonly used in web applications to get products, users, posts, weather information, and other data.

The basic syntax of Fetch API is:

fetch("URL")
Enter fullscreen mode Exit fullscreen mode

For example:

fetch("https://jsonplaceholder.typicode.com/posts")
Enter fullscreen mode Exit fullscreen mode

Here, fetch() sends a request to the given URL.

When the server receives the request, it sends a response. We can handle this response using .then().

fetch("https://jsonplaceholder.typicode.com/posts")
  .then(response => {
    return response.json();
  })
  .then(data => {
    console.log(data);
  });
Enter fullscreen mode Exit fullscreen mode

In this example, the first .then() receives the server response. The response.json() method is used to read the JSON data from the response. The second .then() receives the actual data, which is stored in the data variable.

The basic flow is:

fetch()
   ↓
Request
   ↓
Server
   ↓
Response
   ↓
response.json()
   ↓
Actual Data
Enter fullscreen mode Exit fullscreen mode

Fetch API can also be used to send data to a server using methods such as POST, PUT, PATCH, and DELETE.

For example, a POST request can be written as:

fetch("https://example.com/users", {
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    name: "John",
    age: 25
  })
});
Enter fullscreen mode Exit fullscreen mode

Fetch API is very useful in modern web development because it allows JavaScript applications to communicate with backend servers and APIs without reloading the entire webpage.

In simple words, Fetch API is a way for JavaScript to send requests to a server and receive or send data.

Top comments (0)