What is the Fetch API?

Web developers have used XMLHttpRequest for years, but in recent times, we can see how Fetch API has taken over. While Fetch API and XMLHttpRequest are very similar, Fetch API is preferred.

XMLHttpRequest

XMLHttpRequest is a web API that requests or manipulates data to and from a web server using HTTP.

XMLHttpRequest allows us to fetch data without reloading the entire page. This significantly improves the user experience as users won't have to refresh the page to see new data.

Fetch API

Fetch API allows us to get data from a local or remote server via a RESTful API. It is a promise-based asynchronous API where we can either await it or use promise chaining to get the response. This is where XMLHttpRequest and the Fetch API differ. Fetch API uses promises which makes the code clean and provides more flexibility.

We use the fetch() method to make an API request to perform CRUDCRUD refers to the four basic operations a software application should be able to perform; Create, Read, Update, and Delete. operations on the server. This method will return a promise that, when resolved, responds to that API request.

Parameters

We send a few parameters or objects with our API request. Each of them provides a way to send customized requests.

Method

We can use our fetch() method with request methods like GET, POST, PUT, and so on. For example, if we want to make a POST request, we would do something like this:

fetch('https://jsonplaceholder.typicode.com/posts', {
method: "POST",
body: JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1,
}),
headers: { "Content-type": "application/json; charset=UTF-8" }
})
.then(response => response.json())
.then(json => console.log(json));
.catch (err => console.log(err));

Lines 1–4: The fetch() method takes a RESTful API endpoint as its first argument. The second argument, an object, is optional when we use GET. We set our object, which includes three keys:

  • Method

  • Body

  • Headers

Lines 6–8: Since the fetch method is a promise-based API, we will use the then and catch block. The then() function is to handle the response from the JSONPlaceholder API. The catch() function is responsible for error handling.

URL

The URL is a RESTful API endpoint that we request with different HTTP methods. In the example above, the URL is https://jsonplaceholder.typicode.com/posts.

Body

The body is specific to some HTTP methods like POST, PUT, and so on. The body can include any information we want to send with our request. It can be any of the following:

  • String object

  • ArrayBuffer

  • TypedArray

  • DataView

  • FormData

Note: The GET and HEAD method can't have a body.

Headers

Headers are the additional metadata associated with that API to let the server know what type of data is being fetched. It is also generally used to handle API keys to authenticate the user.

Referral

We use referrals if we want to include a referrer of the request, such as referrer, no-referrer, and so on. It is an optional property, but it is helpful for security purposes.

Mode

This contains the mode of the request. We have three modes, cors, same-origin, and no-cors.

  • Cors: This allows cross-origin requests, which means we can request anything from a different source without the cors error. For example, most follow the CORS policy if we want to access third-party APIs.

  • Same-origin: If we request from a different origin, it will throw an error and wouldn't let us access it.

  • No-cors: This allows a limited set of headers and methods. Only the POST, HEAD, and GET methods will work.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved