Fetch API 101
Tags: javascript, promises, fetch, api
Published: 2019-06-10 16:36:40

---
title: Fetch API 101
published: true
description: A short write-up of the fundamentals of the Fetch API as taught by the Net Ninja
tags: javascript, promises, fetch(), api
cover_image: https://images.unsplash.com/photo-1508814307259-8fcbace8db3b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1050&q=80
---

<u>Credit</u>: This sharing is based on my learning from  the super awesome <a href="https://www.udemy.com/modern-javascript-from-novice-to-ninja/" target="_blank">The Net Ninja's JavaScript Course on Udemy</a>. 

<u>Pre-requisite</u>: Some (or more) good knowledge of <a href="https://scotch.io/tutorials/javascript-promises-for-dummies" target="_blank"><em>promises</em> is necessary to understand <em>fetch</em></a>.

<h1>What is <em>fetch</em>?</h1>
Simply put it's the modern way of getting data/resources from a server. <em>fetch</em> is supported by <em>promises</em> under the hood.
It replaces the use of <a href="https://www.w3schools.com/xml/xml_http.asp" target="_blank">XMLHttpRequest in making asynchronous calls to networks. 

Due to its newness, <a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API" target="_blank"><em>fetch</em> doesn't work on all browsers yet.</a>

<h1>Calling <em>fetch</em></h1>
To use <em>fetch</em>, simply type <code>fetch()</code> and use one of the following as its parameter:
<ul><li>an API endpoint - for example <em><code>fetch("https://jsonplaceholder.typicode.com/todos/1");</code></em></li>
<li>a local resource - for example <em><code>fetch("todos/vela.json");</code></em></li></ul>

<em>fetch</em> returns a promise which either resolves or rejects which we handle using <code>.then()</code> and <code>.catch()</code>

So a <em>fetch</em> call would look something like below:
```javascript
fetch()
  .then(response => {
    //promise resolved, do something with result
  })
  .catch(err => {
    //promise rejected, handle the error
  });
```
<h1>Accessing the <em>fetch</em> response</h1>
When a promise resolves, <strong>we don't have access to the data we want yet</strong>. 

For example, let's run the following code that will randomly retrieve a piece of advice each time: 
```javascript
fetch('https://api.adviceslip.com/advice')
  .then(response => {
    //promise resolved, do something with result
    console.log('Resolved: ', response);
  })
  .catch(err => {
    //promise rejected, handle the error
    console.log('Rejected: ', err);
  });
```

The code returns a <em>response</em> object. We will now have to call the <em>json</em> method available on the <em>response</em> object to access the returned data. 
<img src="https://thepracticaldev.s3.amazonaws.com/i/4b3owty0pedcwe7b8f3c.png">

<h1>Calling the <em>json</em> Method on the <em>Response</em> Object</h1>
As shown above, <em>json</em> is a method on the <em>response</em> object (which we can see by expanding the <em>__proto__</em> key). 

We need to call the <em>json</em> method on the <em>response</em> object to get the data we need. 

When the <em>json</em> method is called, another promise will be returned which can either be resolved or rejected. So we need to chain the first call to another to manipulate the resulting data.

The way to do this is as below:
```javascript
fetch('https://api.adviceslip.com/advice')
  .then(response => {
    //promise resolved, do something with result
    console.log('Resolved: ', response);
    //new code
    return response.json(); 
  })
  //new code
  .then(data => {
    console.log(data);
  })
  .catch(err => {
    //promise rejected, handle the error
    console.log('Rejected: ', err);
  });
```

Output:
<img src="https://thepracticaldev.s3.amazonaws.com/i/6nii7d4f392hjxf8v2c1.png">

And this is ladies and gentlemen, how <em>fetch</em> works in a nutshell!

<h1>Three Steps to Remember While Working With <em>fetch</em></h1>
<ol>
<li>Call <code>fetch("xyz");</code></li>
<li>Call <code>response.json()</code> on the response</li>
<li>Do something with the data</li>
</ol>

<h1>Note on the <em>Response</em>'s HTTP Status Code</h1>
Take note that <strong><em>fetch</em> doesn't fail even when we call an incorrect end-point/resource</strong>. 

For example, calling a non-existent route like <em>https://api.adviceslip.com/<strong>advicexx</strong></em> won't make the execution jump to the <em>catch</em> block! A <em>resolve</em> is still returned in this case but with the HTTP response code of <strong>404</strong> (instead of <strong>200</strong>).
<img src="https://thepracticaldev.s3.amazonaws.com/i/nrq2r9ocd07mr5wye0eb.png">

So it's a good idea to check the <em>response</em>'s HTTP status code prior to calling <em>json</em> on it. For example using the following code:
```javascript
fetch('https://api.adviceslip.com/advice<strong>xx</strong>')
  .then(response => {
    //promise resolved, do something with result
    console.log('Resolved: ', response);
//new code
    if (response.status === 200) {
      return response.json();
    }
    throw new Error('Resource not found');
  })
  //new code
  .then(data => {
    console.log(data);
  })
  .catch(err => {
    //promise rejected, handle the error
    console.log('Rejected: ', err);
  });

```

Output:
<img src="https://thepracticaldev.s3.amazonaws.com/i/6weyqpvihqxo0eawwqhy.png">

Please check out this entry on Stack Overflow for detailed information about <em>fetch</em> and catching errors: https://stackoverflow.com/questions/38235715/fetch-reject-promise-and-catch-the-error-if-status-is-not-ok