> For the complete documentation index, see [llms.txt](https://edrus.gitbook.io/mt-it/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://edrus.gitbook.io/mt-it/2nd-month/week-5/rest-representational-state-transfer/the-fetch-api.md).

# The Fetch API

A modern replacement for XMLHttpRequest

<figure><img src="https://miro.medium.com/v2/resize:fit:1400/1*-yw3mCIfvJotovxiydYa1w.jpeg" alt="" height="350" width="700"><figcaption><p>fetch</p></figcaption></figure>

> It is said that **“Necessity is the mother of all inventions”** and that’s what fueled the development of Fetch API. But before digging deeper into the Fetch API let’s dive into the history behind it. I know I know what’s going on in your mind but I will keep it short.

## **AJAX** <a href="#ed7c" id="ed7c"></a>

**Before `AJAX` (Asynchronous JavaScript and XML) concept was introduced, to update the portion of a page, browsers at that time used to make a request for a full web page to the server, after the request was received by the server, it used to create and return a page to the browser as a response**. **It means that even for a small change the page was loaded entirely**. That was bad right? very very bad.\
After `AJAX` came into the world of internet, it changed the traditional way of updating the page. With `AJAX`, Web applications were able to send and retrieve data from a server **asynchronously** (in the background) without interfering with the display and behaviour of the existing page.

## **XMLHttpRequest** <a href="#id-69ed" id="id-69ed"></a>

In 2006 the **World Wide Web Consortium** published a Working Draft specification for the `XMLHttpRequest` object. **`XMLHttpRequest` object is used to retrieve data from a server asynchronously**. Wait for a second, what did you just said, yes you heard it clearly. In the initial stages, `XMLHttpRequest` used to fetch **`XML`** data over **`HTTP`** hence the name. But today it can be used with protocols other than **`HTTP`** and it can fetch data not only in the form of **`XML`** but also **`JSON`**, **`HTML`** or **plain text**.

> The original concept behind the *`XMLHttpRequest`* object was originally created by the developers of Outlook Web Access (by Microsoft).

So let’s try with an example, we will make a simple request using `XMLHttpRequest`, get a response and parse it as `JSON`.

We need **two** listeners to be set to handle the success and error cases and a call to `open()` and `send()`. The response from the server is stored in the **`responseText`** variable, which is converted to **JavaScript object** using `JSON.parse()`.

> We have used `XMLHttpRequest` for several years to request data other than `XML`, and that’s where the confusion starts when beginner try to learn how to make an asynchronous request in JavaScript.
>
> Isn’t there a cleaner and simple API to make an asynchronous request? well yes, there is and for that, we need to get back to present. So Let’s get back to the present.

## **Fetch** <a href="#id-03c1" id="id-03c1"></a>

Fetch is a new **native JavaScript API**, supported by most browsers today. **Fetch allows you to make network requests similar to `XMLHttpRequest`**. According to [Google Developers Documentation](https://developers.google.com/web/ilt/pwa/working-with-the-fetch-api) Fetch makes it easier to make asynchronous requests and handle responses better than with the older `XMLHttpRequest`. **It is an improvement over the `XMLHttpRequest` API**. **The main difference between Fetch and `XMLHttpRequest` is that the Fetch API uses Promises, hence avoiding callback hell**.

> If you are new to **promises** then check out [JavaScript Promises: an Introduction](https://developers.google.com/web/fundamentals/primers/promises) . You can make use of [**polyfill**](https://github.com/github/fetch) for [**browsers that are not currently supported**](http://caniuse.com/#feat=fetch).

### **Fetch Interfaces** <a href="#id-4146" id="id-4146"></a>

The Fetch API has following interfaces

* [**`fetch()`**](https://developer.mozilla.org/en-US/docs/Web/API/Fetch): The `fetch()` method used to fetch a resource.
* [**`Headers`**](https://developer.mozilla.org/en-US/docs/Web/API/Headers): Represents response/request headers, allowing you to query them and take different actions depending on the results.
* [**`Request`**](https://developer.mozilla.org/en-US/docs/Web/API/Request): Represents a resource request.
* [**`Response`**](https://developer.mozilla.org/en-US/docs/Web/API/Response): Represents the response to a request.

### **Making a request using fetch()** <a href="#beb0" id="beb0"></a>

A [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/GlobalFetch/fetch) function is available in the global **`window`** object. **The `fetch()` function takes one mandatory argument, the path to the resource you want to fetch**. **It returns a `Promise`, whether it is successful or not**. If request is successful `.then()` function will receive **`Response`** object, if request fails then `.catch()` function will receive an **`error`** object

### **The Response Object** <a href="#d921" id="d921"></a>

The above code makes use of Fetch API and makes a call to GitHub to fetch data about the user. **When the promise is resolved we get a `Response` object in return**. But wait, if you try logging `Response` object on the console you will find that it didn’t have the data which we want. That’s because a `Response` object has information about the response itself. To actually get the data, we need to get the body of the response.

<figure><img src="https://miro.medium.com/v2/resize:fit:1400/1*2M6A7Op4LuAsOqFfzFQ1ZQ.jpeg" alt="" height="146" width="700"><figcaption><p>Response object</p></figcaption></figure>

**Since the Github API we’re using will return `JSON` to us, the returned response will have `.json()` method. We just need to call `.json()` on the response variable. The `.json()` method on a `Response` object returns a `Promise`, so we need to chain on another `.then()`.**

<figure><img src="https://miro.medium.com/v2/resize:fit:1400/1*YnFgfLu3b2GrKkVEuywn4w.jpeg" alt="" height="495" width="700"><figcaption><p>Extracted JSON object from Response body</p></figcaption></figure>

### **Headers Object** <a href="#c638" id="c638"></a>

The `Headers` interface allows you to create your own headers object via the [`Headers()`](https://developer.mozilla.org/en-US/docs/Web/API/Headers/Headers) constructor. A headers object is a collection of name-value pairs.

### **Supplying options to fetch()** <a href="#b1b4" id="b1b4"></a>

The `fetch()` method accepts an optional second parameter, an `init` object that allows you to customise the request.

### **Request Object** <a href="#d52f" id="d52f"></a>

The **`Request`** Object represents a resource request. Instead of passing an `URL` of the resource into the `fetch()` call, you can create a request object using the [`Request()`](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) constructor, and pass that as an argument to `fetch().` By passing Request object to the `fetch()`, you can make customised requests.

## **Conclusion** <a href="#id-1465" id="id-1465"></a>

Definitel&#x79;**,** `XMLHttpRequest` wasn’t made for the things we are using it today. Also, it’s API is kinda messed. The `Fetch` API makes it easier to make asynchronous requests and handle responses better than using an `XMLHttpRequest`. `Fetch` allows us to create a better API for the simple things, using modern JavaScript features like `promises`.

Let’s start fetching !!
