Fetch API: Basics
Tags: javascript, webdev, api
Published: 2021-08-15 15:41:40

**Fetch** in layman term means "to get".
**API** is an acronym for Application Programming Interface.

**What exactly is an API ?**
To go by proper definition,
>An API (Application Programming Interface) is a set of features and rules that exist inside a software program (the application) enabling interaction with it through software

Now imagine you have an application or a program in your system which needs some data stored at a remote server. For your program to access that data it needs to let the server know about its requirement. And for this purpose it requires a communication interface through which the program can convey its request to the server and the server can respond in a specific format. This interface or the set of rules which our program uses to communicate with other software or server is called Application Programming Interface.

**Fetch API**
So, Fetch API provides this interface for your programs to be able to send requests to a URL or a remote server and recieve response based on that request in a hassel free way.

In this blog we are going to make a basic app around Fetch API, where we will fetch random dog images from the URL `https://random.dog/woof.json`, by following these steps:
1. [Setting up files](#step-1)
2. [Writing Fetch API function](#step-2)
3. [Converting ReadableStream into JSON](#step-3)
4. [Accessing Image URL from the fetched data](#step-4)
5. [Inserting Image URL in img tag](#step-5)
6. [Adding Event Listener on Button](#step-6)

So let's get started!

### 1. Setting up files <a name="step-1"></a>
Create an HTML file `index.html` with a button and an image tag. The images we will get as response will be displayed here, so for now we are keeping the value of `src` attribute as `src="#"`. You can also add an `h1` tag for heading.

```html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Random Dogs</title>
</head>

<body>
  <h1>Random Doggies, Woof!</h1>
  <button id="getImage">Get Doggie</button>
  <img src="#" alt="dogs" id="images" class="img-class">
</body>

</html>
```
For writing our JavaScript code, create a `main.js` file and include it in the HTML file with the help of `script` tag. Place script tag inside the `head` tag.

```html
<script defer src="./main.js"></script>
```

Also create a `style.css` file for a little styling, so that the images won't be too large. Add the `link` tag inside the head tag.

```html
<link href="./style.css" rel="stylesheet"></link>
```
```css
body{
  margin: 0;
  text-align: center;
}

.img-class{
  display: none;
  width: 240px;
  margin: 2rem auto;
  border-radius: 0.5rem;
}

button{
  width: 10rem;
  height: 2rem;
  border-radius: 0.5rem;
  border: 2px solid black;
  font-size: 1rem;
  cursor: pointer;
  margin: 1rem;
}
```

### 2. Writing Fetch API function <a name="step-2"></a>
JavaScript provides us with a `fetch()` method, which we are going to use to make our request. 
`fetch()` method takes the URL where we want to send request as a parameter and returns a promise.

**What is a promise?**
Imagine it like, the fetch method promises our program to wait for it and it will either bring back the requested response or will give the reason why it was not able to fulfill its promise.

```js
function fetchData(){
  fetch("https://random.dog/woof.json")
    .then(response => console.log(response))
    .catch(err => console.log(err))
}
fetchData();
```
`fetchData()` invokes the function, so when you run the app as soon as the JavaScript file is loaded it will run the `fetchData()` function.

In your browser at this point you might be able to see something like this:
![web-page-screenshot](https://github.com/shraddha-1402/Fetch-API-Basic-App/raw/main/previewSS.png)

Right click on the page, and click on `Inspect element`, in the `console` opened, you can see a `Response` object like this:
![response-obj-screenshot](https://github.com/shraddha-1402/Fetch-API-Basic-App/raw/main/responseObjSS.png) 

Since you got the response it means our request was responded with proper data and no error occurred.

On expanding this object, you can see the `body` field. This field contains the data we require but right now its in `ReadableStream` format. So, we need to convert it into a readable format that is a `JSON object`.

### 3. Converting ReadableStream into JSON <a name="step-3"></a>

```js
function fetchData(){
  fetch("https://random.dog/woof.json")
    .then(response => {
      return response.json()
    })
    .then(jsonData => console.log(jsonData))
    .catch(err => console.log(err))
}
fetchData();
```
Doing `response.json()` will convert the `ReadableStream` into json format. But since its not sure that the `ReadableStream` will definitely be downloaded and is convertible to JSON format, `response.json()` returns a promise, and if its resolved we get the data.

Now refresh the page and see for yourself if the data is properly converted into json format or not.

### 4. Accessing Image URL from the fetched data <a name="step-4"></a>
Now since we got the JSON, let's extract the `url` property by changing the line
```js
jsonData => console.log(jsonData)
```
with this
```js
jsonData => console.log(jsonData.url)
```

### 5. Inserting Image URL in img tag <a name="step-5"></a>
For updating the `src` attribute of `img` tag we need to access the tag in our JavaScript file, and update the `src` attribute with `jsonData.url`

```js
const imgTag = document.querySelector("#images");
function fetchData() {
  fetch("https://random.dog/woof.json")
    .then(response => response.json())
    .then(jsonData => {
      imgTag.style.display = "block";
      imgTag.setAttribute("src", `${jsonData.url}`);
    })
    .catch(err => console.log(err))
}
fetchData();
```

### 6. Adding Event Listener on Button <a name="step-6"></a>
Since we want to fetch a random image everytime we click the `button` and not when we refresh the page, we need to add an `eventListener` to our `button` and remove `fetchData()` call.

```js
const getButton = document.querySelector("#getImage");
getButton.addEventListener("click", fetchData);
```

Now, after putting together our whole JavaScript code, it would look like: 

```js
const getButton = document.querySelector("#getImage");
const imgTag = document.querySelector("#images");

function fetchData() {
  fetch("https://random.dog/woof.json")
    .then(response => response.json())
    .then(jsonData => {
      imgTag.setAttribute("src", jsonData.url);
      imgTag.style.display = "block"; // to unhide img tag
    })
    .catch(err => console.log(err))
}

getButton.addEventListener("click", fetchData);
```
This is how our app would look:
![fetch-api-app-working](https://github.com/ath-github/a/raw/main/ezgif-1-9e66a7ae008f%20(1).gif)

Here, our basic Fetch API app is completed. The whole code is hosted on my GitHub, you can check out this [link](https://github.com/shraddha-1402/Fetch-API-Basic-App) and follow along with each commit.
Also if you want to read more about `document.querySelector()`, `setAttribute()`, `addEventListener()`, etc., read my blog [DOM Manipulation](https://dev.to/shraddha1402/dom-manipulation-hands-on-34m4) for better understanding. 

Happy Coding!