Beginners Guide To Fetching Data With (AJAX, Fetch API & Async/Await)
/[Abejide Femi Jr]\s/

/[Abejide Femi Jr]\s/ @bjhaid_93

About: passionate javascript dev

Location:
lagos
Joined:
May 8, 2018

Beginners Guide To Fetching Data With (AJAX, Fetch API & Async/Await)

Publish Date: May 20 '18
321 36

Introduction

In this tutorial, I will be explaining how to fetch data asynchronously from an external API using web technologies like AJAX, Fetch API and Async/Await.

How To Fetch Data From An External API

AJAX

AJAX stands for Asynchronous Javascript and XML, it is a set of web technology to send and receive data asynchronously from a client or server, it is done behind the scene and you don't need to reload the webpage, JSON(Javascript Object Notation) have actually replaced XML(eXtensible Markup Language), most of the API's returns JSON data, AJAX can also return plain text.

Below is a description of how AJAX works

a
Request is being sent by making an AJAX call, Data in JSON format is being fetched asynchronously from the server and page content is being updated without reloading your webpage, we can fetch data from our local machine or server, public API.
I'll be demonstrating in the code below how to get data from Github API, an external API with AJAX.

    //Create the XHR Object
    let xhr = new XMLHttpRequest;
    //Call the open function, GET-type of request, url, true-asynchronous
    xhr.open('GET', 'https://api.github.com/users', true)
    //call the onload 
    xhr.onload = function() 
        {
            //check if the status is 200(means everything is okay)
            if (this.status === 200) 
                {
                    //return server response as an object with JSON.parse
                    console.log(JSON.parse(this.responseText));
        }
                }
    //call send
    xhr.send();
    //Common Types of HTTP Statuses
    // 200: OK
    // 404: ERROR
    // 403: FORBIDDEN
Enter fullscreen mode Exit fullscreen mode

Below is the data
a

Fetch API

It is the newest standard for dealing with HTTPRequest, it is part of the window object, and we can easily fetch data from an external API as well.Fetch returns Promises
I'll be demonstrating in the code below how to get data from Github API, an external API with Fetch API.

    //call the fetch function
    fetch('https://api.github.com/users')
    .then(res => res.json())//response type
    .then(data => console.log(data)); //log the data;

Enter fullscreen mode Exit fullscreen mode

Below is the data

Async/Await

It is part of the ES7 standard, it is now fully implemented in Chrome, we add async to the function and it returns a Promise.
I'll be demonstrating in the code below how to get data from Github API, an external API with Async/Await.

    async function getData() 
        {
            //await the response of the fetch call
           let response = await fetch('https://api.github.com/users');
            //proceed once the first promise is resolved.
           let data = await response.json()
            //proceed only when the second promise is resolved
            return data;
        }
//call getData function
getData()
.then(data => console.log(data));//log the data
Enter fullscreen mode Exit fullscreen mode

Below is the data
a

Note

Any of the three methods can be used to fetch data, i actually prefer to use Fetch API, and there are several methods(axios, superagent e.t.c) apart from three methods, not discussed in this context, API's are different, how request is being taken and how response is being served differs, documentation is being provided for external API's to guide you.
I hope you enjoyed the tutorial, Thanks For Reading.

Comments 36 total

  • Itachi Uchiha
    Itachi UchihaMay 21, 2018

    Is there a way extract data from promise? For example, I don't want to use like this:

    blah().then()
    
    • /[Abejide Femi Jr]\s/
      /[Abejide Femi Jr]\s/May 21, 2018

      don't know of any, apart from .then(), and .catch() -> for errors.

    • Pierre Joubert
      Pierre JoubertMay 24, 2018

      Do you not like the syntax? Or do you not want to deal with promises?

      • Itachi Uchiha
        Itachi UchihaMay 24, 2018

        I just wonder about assign result to a variable. I don't wan't to use then all time. For example:

        const myResults = fetch('site.com')
           .then(resp => resp.json())
           .then(obj => obj)
        
        console.log(myResults)
        // { name: 'John', surname: 'Doe' }
        
        
        • Pierre Joubert
          Pierre JoubertMay 24, 2018

          I just did this and it seemed to work:

          var foo = null;
          fetch('https://jsonplaceholder.typicode.com/posts/1')
             .then(resp => resp.json())
             .then(obj => foo = obj)
          

          Then foo is accessible object like: foo.title
          "sunt aut facere repellat provident occaecati excepturi optio reprehenderit"

          • Itachi Uchiha
            Itachi UchihaMay 24, 2018

            Thanks a lot. That's exactly what I want.

    • Maccabee
      MaccabeeMay 24, 2018

      You can await Promises.

      const data = await blah();
      

      That's how async/await compile with babel, into Promises.

      • Itachi Uchiha
        Itachi UchihaMay 24, 2018

        Thanks a lot. It worked :) Why I didn't try that. I think I was confused.

      • Pierre Joubert
        Pierre JoubertMay 24, 2018

        Ah much better xD

  • Adrian B.G.
    Adrian B.G.May 21, 2018

    And while learning these, you may want to know they invented a new way of fetching a resource youtu.be/Wi_PhaFdjlo

  • Mattias Petter Johansson
    Mattias Petter JohanssonMay 21, 2018

    Note that response.json() returns a PROMISE. This is a common misconception. This article is a wee bit misleading in the async / await example, the data variable will be a promise but the example sort of makes it seem like response.json() is sync by not using await in front of the call.

  • alokz diptim!
    alokz diptim!May 21, 2018

    Won't Ajax jquery be easier than this ?

    • /[Abejide Femi Jr]\s/
      /[Abejide Femi Jr]\s/May 21, 2018

      with sound knowledge in vanilla JavaScript, you might not need jquery in your code, i prefer Ajax with vanilla JavaScript to Ajax with jquery.

    • Maccabee
      MaccabeeMay 24, 2018

      jQuery is a very large library if you just want Ajax

  • Lew Yuburi
    Lew YuburiMay 21, 2018

    Can I translate this to spanish in my Medium blog? I will reference this post

  • Eri Pançi
    Eri PançiMay 25, 2018

    Great article. It inspired me to experiment with API's since I'm in a period of learning Javascript. But doing a small project I got a problem, and since I didn't find an article online, I thought to ask here, hope I'll be clear:
    Is there a possibility to make the async function and getData in different functions or objects?

    Because in your example both these are immediately after one another. But after some time my code gets messy, so I wanted to make the function and the call in different objects.

    Thank you.

    • /[Abejide Femi Jr]\s/
      /[Abejide Femi Jr]\s/May 25, 2018

      Hello, can you share your code

      • Eri Pançi
        Eri PançiMay 25, 2018

        since I'm working on Glitch, here is the full project: glitch.com/edit/#!/titanium-freeze

        As you can see, inside the function getMovies it's async function and getData(). Can I make these two not inside one function but instead in two? One can get the data, the other can show it?

        Thank you.

        • /[Abejide Femi Jr]\s/
          /[Abejide Femi Jr]\s/May 25, 2018

          Can't access that URL, can you paste your code here please, or possibly push to GitHub and send the URL

          • Eri Pançi
            Eri PançiMay 25, 2018

            Strange. Anyway here it is in Github: github.com/erip2/MovieApp/

            • /[Abejide Femi Jr]\s/
              /[Abejide Femi Jr]\s/May 26, 2018

              firstly, what are the datas you are trying to get from the API, i can also see you are trying to persist to sessionstorage, es6 classes could make the code look cleaner a bit tho, have a separate class for your ui, another class for you Session or local storage, then another class for the Movie.

              • Eri Pançi
                Eri PançiMay 26, 2018

                The data I'm getting from API is an array of movie titles the user search. Then when user clicks for details, I save the movie ID in sessionStorage to open a new window with that movie details.

                That was exactly why I asked, to do these in different places in my code. Could I do these in different objects or should I read about JS classes since I don't know them very well to use it?

                Thanks again.

  • db325
    db325Jul 10, 2018

    When working with the fetch API, how would I put in my access tokens and keys with the request? I've been stuck for two days in this Twitter app.

  • Deni Toshevski
    Deni ToshevskiOct 25, 2018

    How would you loop through the received data, if you want let's say just a certain part of it to display?

  • Kiquenet
    KiquenetFeb 12, 2019

    alternatives to Promise?

    let vs var ?

  • ADITYA727
    ADITYA727Mar 15, 2019

    Sir , I have url and api_key than how can fetch data ...........

  • Ana María Benites Rodríguez
    Ana María Benites RodríguezMay 26, 2019

    Nice, thanks for the information!

  • Ifeanyi onuoha
    Ifeanyi onuohaJan 12, 2020

    Great article. It cleared me perfectly in a very brief and precise manner. Thanks

  • filza
    filzaJan 31, 2020

    when i use fetch API I AM GETTING NOTHING ON MY LOCAL HOST

    THIS IS MY CODE
    var express = require("express");
    var app = express();
    app.listen(3000, () => {
    console.log("Server running on port 3000");
    });

    const fetch = require('node-fetch');
    fetch('URL')
    .then(res => res.json())//response type
    .then(data => console.log(data));

Add comment