How to use fetch api in JavaScript to get data?

By Gulshan Saini
Published in JavaScript
June 15, 2020
1 min read

The Fetch API provides an interface for fetching resources similar to XMLHttpRequest (XHR). The main difference is that the Fetch API uses Promises which make working with request and response easier, avoiding the callback hell.

The Fetch API provides fetch() method defined on window object which can be used to make network request.


  .then(response => response.json())
  .then(data => console.log(data))

Let’s see it in action!

Step 1

We will start with minimal markup required for this demo

<button id="fetchdata">Get Details</button>
<div id="result"></div>

The button having id of fetchdata when clicked, will fetch data from URL https://api.github.com/users/gulshansainis and display the result in <div id="result"></div>. The URL we are using is the public URL of my GitHub profile. If you open the above URL directly in the browser you should see the JSON result that we expect form fetch API.

Step 2

Next, we can create an event listener for button having id fetchdata, so that when it is clicked the listener

  • sets the text content of result div “Loading…”
  • when the result is available from API it updates the content of result div
const fetchDataBtn = document.querySelector('#fetchdata')
const result = document.querySelector('#result')

// gets data from API and sets the content of #result div
const getData = function() {
  result.innerText = 'Loading....'
    .then(res => res.json())
    .then(data => {
      result.innerText = JSON.stringify(data, null, 2)
    .catch(error => console.log(error))

// add event listener for #fetchdata button
fetchDataBtn.addEventListener('click', getData)

Let me walk through the above code line by line

  • const fetchDataBtn = document.querySelector("#fetchdata"); - handler for fetch button
  • const result = document.querySelector("#result"); - handler for result div
  • getData() function
    • First, we are setting inner text of result div to “Loading…” result.innerText = "Loading....";
    • Next, we make fetch() request fetch("https://api.github.com/users/gulshansainis"). When this piece of code is executed, browser immediately returns a Promise object. A Promise could be in pending i.e. initial state, fulfilled i.e. success, and rejected state.
    • Once the Promise is in fulfilled state it returns a Response object. Within the first then() we can call this json method to return the response body as JSON i.e. then((res) => res.json())
    • The previous statement i.e. res.json() again return a Promise so we need to again call the then() method. Inside then() method we are setting the data recieved from API inside the result div i.e. result.innerText = JSON.stringify(data, null, 2);. Since, it return a JSON object I have used the JSON.stringify(...) to pretty print result on screen.
    • Last statement is to catch any error that might be caused due to wrong resource URL, server error or network error.
  • At last, we setup the fetchDataBtn listener that will listen for click events and make a Fetch API request. fetchDataBtn.addEventListener("click", getData);

A working demo of code discussed above

Fetch API with Async Await

A more cleaner approach would be to use Fetch API with Async/ Await. Replacing the then() chain with Async/ Await will make code more cleaner and easier to read.

Tip: We should wrap `await` calls in try/catch block to handle any error that might be caused due to wrong resource URL, server error or network error.

Remember - The await keyword only works in async functions


Previous Article
How to diff two files in Visual Studio Code(VSCode)?

Related Posts

JavaScript get tomorrow's date
December 13, 2021
1 min
Gulshan Saini

Gulshan Saini

Fullstack Developer



Subscribe to our newsletter!

We'll send you the best of our blog just once a month. We promise.
© 2022, All Rights Reserved.

Quick Links

Contact UsBrowserCSSPythonPuppeteer

Social Media