DEV Community

Shraddha Gupta
Shraddha Gupta

Posted on

Fetch API: Basics

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
  2. Writing Fetch API function
  3. Converting ReadableStream into JSON
  4. Accessing Image URL from the fetched data
  5. Inserting Image URL in img tag
  6. Adding Event Listener on Button

So let's get started!

1. Setting up files

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.

<!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>
Enter fullscreen mode Exit fullscreen mode

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.

<script defer src="./main.js"></script>
Enter fullscreen mode Exit fullscreen mode

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.

<link href="./style.css" rel="stylesheet"></link>
Enter fullscreen mode Exit fullscreen mode
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;
}
Enter fullscreen mode Exit fullscreen mode

2. Writing Fetch API function

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.

function fetchData(){
  fetch("https://random.dog/woof.json")
    .then(response => console.log(response))
    .catch(err => console.log(err))
}
fetchData();
Enter fullscreen mode Exit fullscreen mode

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

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

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

function fetchData(){
  fetch("https://random.dog/woof.json")
    .then(response => {
      return response.json()
    })
    .then(jsonData => console.log(jsonData))
    .catch(err => console.log(err))
}
fetchData();
Enter fullscreen mode Exit fullscreen mode

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

Now since we got the JSON, let's extract the url property by changing the line

jsonData => console.log(jsonData)
Enter fullscreen mode Exit fullscreen mode

with this

jsonData => console.log(jsonData.url)
Enter fullscreen mode Exit fullscreen mode

5. Inserting Image URL in img tag

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

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();
Enter fullscreen mode Exit fullscreen mode

6. Adding Event Listener on Button

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.

const getButton = document.querySelector("#getImage");
getButton.addEventListener("click", fetchData);
Enter fullscreen mode Exit fullscreen mode

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

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);
Enter fullscreen mode Exit fullscreen mode

This is how our app would look:
fetch-api-app-working

Here, our basic Fetch API app is completed. The whole code is hosted on my GitHub, you can check out this link and follow along with each commit.
Also if you want to read more about document.querySelector(), setAttribute(), addEventListener(), etc., read my blog DOM Manipulation for better understanding.

Happy Coding!

Top comments (0)