Author Photo
Christopher Unum I am a software Developer, I write web development tutorials, I also mentor aspiring web developers. s

how to retrieve data from an api using fetch api in javascript


User Name

User Phone

User Address

User age




If you are warming up to become a front-end developer, then knowing how to extract data from an API is vital. APIs are developed by back-end developers and can be accessed by a HTTP request. 

In this tutorial, we will be connecting to a free, open-source API obtained from randomuser.me that generates random user data using Fetch API.

Prerequisite

Basic knowledge of Html, Css and JavaScript (ES 6) is required to fully understand the concepts in this tutorial

What is an API

API stands for Application Programming Interface. An API allows two applications to communicate with each other. 

One example of an API usage in our everyday lives is weather data found on platforms like Google Search or Apple's Weather App. Google don't generate their weather data, they rely on third-party APIs to obtain weather data for search results.

An API provides a Layer of Security, your data is never fully exposed to the server and Also the API developers decide which information are made available, this limits access to only required information rather than full control.

Randomuser API

As mentioned earlier, we will be connecting to the randomuser API to obtain random user data. After we send an HTTP request to the API endpoint, the API will provide us with data containing the user's information which would be obtained as a JSON object. Below is a sample of a JSON object obtained from randomuser.me.

{
    "results": [
      {
        "gender""male",
        "name": {
          "title""mr",
          "first""brad",
          "last""gibson"
        },
        "location": {
          "street""9278 new road",
          "city""kilcoole",
          "state""waterford",
          "postcode""93027",
          "coordinates": {
            "latitude""20.9267",
            "longitude""-7.9310"
          },
          "timezone": {
            "offset""-3:30",
            "description""Newfoundland"
          }
        },
        "email""brad.gibson@example.com",
        "login": {
          "uuid""155e77ee-ba6d-486f-95ce-0e0c0fb4b919",
          "username""silverswan131",
          "password""firewall",
          "salt""TQA1Gz7x",
          "md5""dc523cb313b63dfe5be2140b0c05b3bc",
          "sha1""7a4aa07d1bedcc6bcf4b7f8856643492c191540d",
          "sha256""74364e96174afa7d17ee52dd2c9c7a4651fe1254f471a78bda0190135dcd3480"
        },
        "dob": {
          "date""1993-07-20T09:44:18.674Z",
          "age"26
        },
        "registered": {
          "date""2002-05-21T10:59:49.966Z",
          "age"17
        },
        "phone""011-962-7516",
        "cell""081-454-0666",
        "id": {
          "name""PPS",
          "value""0390511T"
        },
        "picture": {
          "large""https://randomuser.me/api/portraits/men/75.jpg",
          "medium""https://randomuser.me/api/portraits/med/men/75.jpg",
          "thumbnail""https://randomuser.me/api/portraits/thumb/men/75.jpg"
        },
        "nat""IE"
      }
    ],
    "info": {
      "seed""fea8be3e64777240",
      "results"1,
      "page"1,
      "version""1.3"
    }
  }

HTML

We need to create a profile page that displays the information obtained from the API.  We will be obtaining the user's name, image, phone, address and age from the randomuser API and rendering it in our HTML code shown below.

<div class="profile-out">
  <div class="profile-in">
    <div class="profile">
      <h3 class="user-name">User Name</h3>
      <div class="user-photo">
        <a href="https://placeholder.com"
          ><img src="https://via.placeholder.com/125"
        /></a>
      </div>
      <p class="user-phone">User Phone</p>
      <p class="user-address">User Address</p>
      <p class="user-age">User age</p>
    </div>
  </div>
</div>

css

Adding styles to our HTML code

.profile-out {
  max-width700px;
  margin0 auto;
  text-aligncenter;
  padding15px 0;
}
.profile-in {
  width93%;
  margin0 auto;
  background#79bdce;
  colorwhite;
  padding15px 0;
}

.profile {
  width93%;
  margin0 auto;
}
.user-photo {
  width125px;
  border-radius50%;
  margin0 auto;
}
.user-photo img {
  border-radius50%;
  border3px solid #47dbe0;
}

Fetch API

Fetch API is a JavaScript API that allows you to make network requests, it is similar to XMLHttpRequest and it is promise-based. Compared to XMLHttpRequest, Fetch API is a simple and clean API that fetches resources from a server.

Using Fetch API is straight forward

fetch("/js/users.json")
  .then((response) => {
    // handle response data
  })
  .catch((err) => {
    // handle errors
  });

The path to access the resources is passed as a parameter in the fetch() method, then the response is accessed using the then() method and finally, we can catch any errors and handle them appropriately.

JavaScript

Now that we understand the Fetch API, we can now use it in our JavaScript code

const displayUserName = ({ title, last, first }) => {
  document.querySelector(
    ".user-name"
  ).textContent = `${title} ${first} ${last}`;
};

const displayUserPhoto = ({ large }) => {
  document
    .querySelector(".user-photo")
    .getElementsByTagName("img")[0].src = large;
};

const displayUserPhone = ({ phone, cell }) => {
  document.querySelector(
    ".user-phone"
  ).textContent = `${phone} / ${cell}`;
};

const displayUserAddress = ({ street, city, state }) => {
  const { name, number } = street;
  document.querySelector(
    ".user-address"
  ).textContent = `${number} ${name}${city}${state}`;
};

const displayUserAge = ({ age }) => {
  document.querySelector(".user-age").textContent = `${age} years old`;
};

const displayUserInfo = (data) => {
  if (!data) return;

  console.log(data);
  //using object destructuring
  const { results } = data;
  const [profile] = results;

  const { name } = profile;
  displayUserName(name);

  const { picture } = profile;
  displayUserPhoto(picture);

  displayUserPhone(profile);

  const { location } = profile;
  displayUserAddress(location);

  const { dob } = profile;
  displayUserAge(dob);
};

const getUserInfo = () => {
  const api = "https://randomuser.me/api/";

  // make API call here
  fetch(api)
    .then((response) => response.json())
    .then((data) => {
      displayUserInfo(data);
    })
    .catch((error) => alert("error getting API resources"));
};
getUserInfo();

We used a lot of Object Destructuring to obtain data from the response. If you are new to ES 6, you can read about it here. In our JavaScript code, the getUserInfo() method uses Fetch API to obtain data from randomuser.me, then the data is then passed on to the displayUserInfo(data) to render the information on our page. 

conclusion

We've come to the end of this tutorial. The best way to learn is to practice and practice some more, so find some free APIs and try using Fetch API to extract data from them.