Skip to content
Related Articles

Related Articles

Improve Article

Working with APIs in JavaScript

  • Last Updated : 07 Aug, 2021
Geek Week

An API is simply a medium to fetch or send data between interfaces. Let’s say you want to make an application that provides the user with some real-time data fetched from the server or maybe even allows you to modify or add data to some other endpoint. This is made possible by the API or the Application Programming Interface.

We will use a simple public API that requires no authentication and allows you to fetch some data by querying the API with GET requests.

https://randomuser.me/ is a website that provides dummy data for random users that we can easily work with. We can get the response by making a request to https://randomuser.me/api/. The JSON response that we receive in the following format.

Javascript




{
    "results": [
        {
            "gender": "female",
            "name": {
                "title": "Miss",
                "first": "Nina",
                "last": "Simmmons"
            },
            "location": {
                "street": {
                    "number": 970,
                    "name": "Eason Rd"
                },
                "city": "Fullerton",
                "state": "Wyoming",
                "country": "United States",
                "postcode": 57089,
                "coordinates": {
                    "latitude": "83.1807",
                    "longitude": "104.7170"
                },
                "timezone": {
                    "offset": "+8:00",
                    "description":
        "Beijing, Perth, Singapore, Hong Kong"
                }
            },
            "email": "nina.simmmons@example.com",
            "login": {
                "uuid": "bd0d135f-84df-4102-aa4f-5baaa41baf5c",
                "username": "yellowfrog722",
                "password": "dawg",
                "salt": "q28gdiyN",
                "md5": "291987daea22bb91775226574925b271",
                "sha1": "a0463a26ea5c2ff4f3ad498fd01c5994926e5021",
                "sha256":
"6583eb74ca08bfac50b3b29aa52c9f02ea5d9d017fef0e5a5a6fae4f5225f928"
            },
            "dob": {
                "date": "1980-11-01T23:10:05.403Z",
                "age": 40
            },
            "registered": {
                "date": "2013-04-02T02:26:52.904Z",
                "age": 7
            },
            "phone": "(216)-693-7015",
            "cell": "(501)-534-9413",
            "id": {
                "name": "SSN",
                "value": "847-09-2973"
            },
            "picture": {
                "large":
                "medium":
                "thumbnail":
            },
            "nat": "US"
        }
    ],
    "info": {
        "seed": "82a8d8d4a996ba17",
        "results": 1,
        "page": 1,
        "version": "1.3"
    }
}

Next you need to have an HTML file for the frontend where you want to display the retrieved data. 



We can use either the “div” tag (block-level) or the “span” tag (inline-level), which will act as a place holder for the information. Using the “id” attribute, we can get the required “div/span” container where we want to place the information.

HTML




<html lang="en">
 
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content=
    "width=device-width, initial-scale=1.0" />
 
  <link id="favicon" rel="icon"
      href="" sizes="16x16" />
       
  <!-- font-awesome library to make the
      webpage more appealing -->
  <link rel="stylesheet" href=
 
  <!-- Internal CSS styling -->
  <style>
    .content {
      text-align: center;
      padding: 30px;
      margin: 0px auto;
    }
 
    .details {
      margin-left: auto;
      margin-right: auto;
    }
 
    img {
      border-radius: 5px;
      box-shadow: black;
    }
 
    table,
    td {
      border-collapse: collapse;
      margin-left: auto;
      margin-right: auto;
      text-align: center;
      padding: 10px;
      border: 1px solid black;
    }
  </style>
</head>
 
<body>
  <div class="content">
    <div class="head">
      <h1 id="head"></h1>
    </div>
    <div class="email">
      <i class="fa fa-envelope" style=
        "font-size: 15px; color: blue;"></i>
      <a href="" id="email"> </a>
    </div>
    <div class="phone">
      <i class="fa fa-phone" style=
        "font-size: 15px; color: blue;"></i>
      <a href="" id="phone"> </a>
    </div>
    <br />
    <div id="user-img"></div>
    <br />
 
    <div class="details">
      <table>
        <tr>
          <td>Age</td>
          <td><span id="age"></span></td>
        </tr>
        <tr>
          <td>Gender</td>
          <td><span id="gender"></span></td>
        </tr>
        <tr>
          <td>Location</td>
          <td><span id="location"></span></td>
        </tr>
        <tr>
          <td>Country</td>
          <td><span id="country"></span></td>
        </tr>
      </table>
    </div>
  </div>
</body>
 
</html>

The script tag will contain the code that will make the API request and handle the response. This needs to be placed within the body tag or as a separate file.

We use the async/await function that basically ensure that the data is displayed even after the page is loaded.

You can use console.log(…) method to check if the user is retrieving correct piece of information. The output for the same can be seen by opening the console window in your web browser (Right Click -> Inspect -> Console or Ctrl+Shift+J in Chrome/Edge).

Javascript




<script>
  const api_url = "https://randomuser.me/api/";
  async function getUser() {
 
    // Making an API call (request)
    // and getting the response back
    const response = await fetch(api_url);
 
    // Parsing it to JSON format
    const data = await response.json();
    console.log(data.results);
 
    // Retrieving data from JSON
    const user = data.results[0];
    let { title, first, last } = user.name;
    let { gender, email, phone } = user;
    let image = user.picture.large;
    let image_icon = user.picture.thumbnail;
    let age = user.dob.age;
    let { city, state, country } = user.location;
 
    let fullName = title + ". " + first + " " + last;
    document.title = fullName;
 
    // Accessing the div container and modify/add
    // elements to the containers
    document.getElementById("head").innerHTML = fullName;
    document.getElementById("email").href = "mailto:" + email;
    document.getElementById("email").innerHTML = email;
    document.getElementById("phone").href = "tel:" + phone;
    document.getElementById("phone").innerHTML = phone;
    // accessing the span container
    document.querySelector("#age").textContent = age;
    document.querySelector("#gender").textContent = gender;
 
    document.querySelector("#location").textContent
            = city + ", " + state;
 
    document.querySelector("#country").textContent = country;
 
    // Creating a new element and appending it
    // to previously created containers
    let img = document.createElement("img");
    let img_div = document.getElementById("user-img");
    img.src = image;
    img_div.append(img);
 
    const favicon = document.getElementById("favicon");
    favicon.setAttribute("href", image_icon);
  }
 
  // Calling the function
  getUser();
</script>

Final code: It is the combination of the above code sections.

HTML




<html lang="en">
 
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content=
    "width=device-width, initial-scale=1.0" />
 
  <!-- font-awesome library to make the
      webpage more appealing -->
  <link rel="stylesheet" href=
 
  <!-- Internal CSS styling -->
  <style>
    .content {
      text-align: center;
      padding: 30px;
      margin: 0px auto;
    }
 
    .details {
      margin-left: auto;
      margin-right: auto;
    }
 
    img {
      border-radius: 5px;
      box-shadow: black;
    }
 
    table,
    td {
      border-collapse: collapse;
      margin-left: auto;
      margin-right: auto;
      text-align: center;
      padding: 10px;
      border: 1px solid black;
    }
  </style>
</head>
 
<body>
  <div class="content">
    <div class="head">
      <h1 id="head"></h1>
    </div>
    <div class="email">
      <i class="fa fa-envelope" style=
        "font-size: 15px; color: blue;"></i>
      <a href="" id="email"> </a>
    </div>
    <div class="phone">
      <i class="fa fa-phone" style=
        "font-size: 15px; color: blue;"></i>
      <a href="" id="phone"> </a>
    </div>
    <br />
    <div id="user-img"></div>
    <br />
 
    <div class="details">
      <table>
        <tr>
          <td>Age</td>
          <td><span id="age"></span></td>
        </tr>
        <tr>
          <td>Gender</td>
          <td><span id="gender"></span></td>
        </tr>
        <tr>
          <td>Location</td>
          <td><span id="location"></span></td>
        </tr>
        <tr>
          <td>Country</td>
          <td><span id="country"></span></td>
        </tr>
      </table>
    </div>
  </div>
</body>
<script>
  const api_url = "https://randomuser.me/api/";
 
  async function getUser() {
   
    // Making an API call (request)
    // and getting the response back
    const response = await fetch(api_url);
 
    // Parsing it to JSON format
    const data = await response.json();
    console.log(data.results);
 
    // Retrieving data from JSON
    const user = data.results[0];
    let { title, first, last } = user.name;
    let { gender, email, phone } = user;
    let image = user.picture.large;
    let image_icon = user.picture.thumbnail;
    let age = user.dob.age;
    let { city, state, country } = user.location;
 
    let fullName = title + ". " + first + " " + last;
    document.title = fullName;
 
    // Accessing the div container and modify/add
    // elements to the containers
    document.getElementById("head").innerHTML = fullName;
    document.getElementById("email").href = "mailto:" + email;
    document.getElementById("email").innerHTML = email;
    document.getElementById("phone").href = "tel:" + phone;
    document.getElementById("phone").innerHTML = phone;
    // accessing the span container
    document.querySelector("#age").textContent = age;
    document.querySelector("#gender").textContent = gender;
 
    document.querySelector("#location").textContent
          = city + ", " + state;
     
    document.querySelector("#country").textContent = country;
 
    // Creating a new element and appending it
    // to previously created containers
    let img = document.createElement("img");
    let img_div = document.getElementById("user-img");
    img.src = image;
    img_div.append(img);
 
    const favicon = document.getElementById("favicon");
    favicon.setAttribute("href", image_icon);
  }
 
  // Calling the function
  getUser();
</script>
 
</html>

Output: 

Random user data

Want to explore the APIs more and dive deeper into it, Refer Public APIs that has a vast collection of publically available APIs to fuel your API exploration journey.

To test an API for the type of response it gives Postman is an amazing application that will fulfill all your needs. You can use Postman API development article to get an insight into, how to use it. Another alternative is, Postman APIs which will help you do the same task on the browser itself.

 

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it’s lowest price ever!




My Personal Notes arrow_drop_up
Recommended Articles
Page :