JS INSiGHTS - The Fetch API

JS INSiGHTS - The Fetch API

Β·

7 min read

Heya fellows, Shobhit here and am back again with the second chapter of JS INSiGHTS. This article is going to be all about the infamous Fetch API.
But, wait a minuteβœ‹

What exactly is an API πŸ€”

Well, as a developer you may have encountered this term several times and if you still scratch your head when someone asks you to explain the term API, then please let me do the work for you.
API is a code written by someone else and you can use that code in your application.
Ya, that's it. Sometimes, you gotta pay for the service and sometimes not, it depends upon the provider. In most of the API's, we also get a unique secret key to access that API.
Suppose, we want to make the login functionality in our sites. But we don't want the user to enter their email, then their password and then verify their email and so on. Now, we can use sign-in-with-google API to make it hassle-free experience. Because we know almost everyone uses gmails and also they are highly secured. Hence, we don't need to write code login functionality from scratch.
Now, let's get started 🍿

Table of Contents :

Intro to fetch πŸ“– -

The fetch API is a web API standard available on all browsers and it provides Javascript, methods to make HTTP requests.
To make the request, the API provides a fetch() method and as it is a web API, the fetch function belongs to the window object.
Syntax : fetch(url, {options})

  • url - the URL to access. Remember, the URL should be inside quotes.
  • options - optional parameters: methods, headers etc.

The fetch() returns a promise after making requests to a URL. So, we should have some knowledge of how to deal with the promise object. Don't worry, if you have no clue about promises. As of now, just remember ⬇️

The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

That means after fetch has completed calling the API, we can use .then, .catch etc. to resolve response and catch errors respectively.
If nothing is making sense to you, then just keep reading, you will eventually understand at the end of the article.

GET request using fetch 🀲:

  • Unlike XHR, it's quite easy to get data using fetch(). The API from which we are going to fetch data is reqres.in
    fetch("https://reqres.in/api/users/2")
    .then(res => res.json())
    .then(data => console.log(data));
    
    Now, let me make the above code understandable
  • As told earlier, fetch is a promise-based API ⏬ j1iWDGm - Imgur.png Hence, to resolve this promise we will use .then method. Now, let's understand our [[PromiseResult]] i.e. Response a bit deeper.
  • ascv.png This Response object contains pretty much all the information about the request and the response of the network request such as status, URL, headers, body content etc.
    Inside the __proto__ property, we can see various methods that can be used on the response object. Functions like json, blob, text, formData and arrayBuffer are helpful to us for getting the exact data.
  • img In the above figure, we can see two promises. The former is returned when fetch calls the URL and the latter one by res.json() method and to resolve this we will use .then again. We can also see the data that we wanted. 🀩
  • Okay, one more example. This time, let's try hashnode.com. img I have used res.text() here because it's obvious that it's not going to return json. So, I hope that now you don't have to cram the above syntax and a quick tip ⚑for beginners -
    Always use res.blob() while fetching an image(.png, .jpg) or video(.mp4, .ogg).

Handling errors πŸ†˜:

Now, let's try to fetch a wrong URL img We got a 404 error which implies that a user with an id of 61 is not found. Now, what I want to emphasize that the error is not in the fetch API. The error lies within the URL that we are providing to the fetch.
Let's try to log the response as we did above. Upon logging, we found that the status & ok property of the response object are 200 and true respectively. This implies that fetch is able to get the response from the provided URL. So, to handle our 404 error in this case, what we can do is πŸ‘‡ img One more thing that I want to highlight here is that there might be some cases when the fetch API itself doesn't work. This can happen when we are having some kind of network issues.
To handle this error, we can use .catch method. img

POST request using fetch 🏹 :

While developing a web application you must have encountered several times when you need to send data to the server. Let's learn how we can achieve this using fetch(). There are 3 main parameters that we need to provide while making a POST request using fetch.

  • method : HTTP request methods.(The default method is GET).
  • body: The data that we need to send. (body data type must match "Content-Type" header)
  • "Content-type" : Present inside headers

Above all the options, the one that might seem a bit confusing is Content-type. We don't need to understand all about headers and all the stuff.
We just need to know why do we need to set content-type ❔.

HTTP headers let the client and the server pass additional information with an HTTP request or response. Content-Type in the header of an HTTP request specifies to the server what type of data it should expect(i.e. whether it should be XML,json etc.). If a server allows and accepts multiple types of content it can use this field to know how to interpret the body of the request. - Reference

And, Here's the code πŸ₯πŸ₯ img And very successfully we are able to send data to the server and get the response.

  • JSON.stringify() converts our JSON data to a JSON string format.
  • application/json is set when we have to send JSON data to the server. See here in detail about content-type.

TIP πŸ•―οΈ:

  • Now, we have covered a lot about fetch. But, there is one thing that I still need to tell you guys, so that you don't feel dizzy 😡 while working with fetch on a real-world project.
    You must have an idea of the CORS mechanism.

CORS is an HTTP-header based mechanism that allows website on one URL to request data from another URL. It allows the server to specify the origins (other than self) that can request data from it.

So the very, first question, that you would want to ask is "how the hell we were getting a response until now ?" To allow websites of different origin to request data, we have to set "access-control-allow-origin" response header on the server-side.
The 'reqres' API that we used throughout our article has set the above header to '*', so that anyone requesting the data should not face CORS errors. See the below image. img Now, try fetching data from youtube from any URL other than youtube.

Exercise πŸ§‘β€πŸ«

First things first, here's the solution of the exercise from my previous article

// Google Script
<script src="https://google-analytics.com/analytics.js" async></script>
// jquery CDN 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js" defer></script>
// AdSense
<script src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js" async></script>

As the concept of fetch API is somewhat trickier, I have got two quick and quirky exercises for you.

  1. Download an image from the internet using fetch() and insert it into src attribute of <img>. Sample Image
  2. Fetch multiple image files using fetch() and insert each of them into a separate img tag.
    const images = [
    https://i.imgur.com/B4qYYUo.png?1,
    https://i.imgur.com/0jLEcuB.png,
    https://i.imgur.com/9SNGN0j.png
    ]
    
    The answers will be revealed in my next article, till then stay tuned.
    Well, Thanks for reading πŸ’œ and if you want more such content do subscribe to my newsletter. Also, you can follow me on 🐦 to get daily updates about the web world πŸ€—