Trusted answers to developer questions

Make API calls with JavaScript

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

Overview

There are a variety of ways to make an API request with JavaScript, ranging from using plain JavaScript to jQuery to additional tools that greatly simplify the process. In this shot, we’ll utilize a standard JavaScript technique and change our code to make our API requests in a variety of ways. We’ll also learn about several tools for working with asynchronous programming in the process. APIs, after all, are asynchronous. While we’ll only use the async tools we learn to make API calls in this part, the same tools may also be used for other asynchronous JavaScript tasks.

We’ll make an API request in an old-fashioned manner using only vanilla JavaScript. This old-fashioned method is used by all of the tools that jQuery utilizes to perform API requests. However, we won’t cover the jQuery technique in this section because the Fetch API is a far superior option. Fetch is likewise based on this time-honored method. So, while we may not utilize this strategy here (though we certainly may!), we'll have a better knowledge of how technologies, like Fetch, function when we use them later.

Let's get started

The sample code below is available at the end of the shot. To create this project from scratch, we’ll need to include a webpack environment, which we can either build afresh or get from the sample code at the end of this shot.

In this shot, we won’t require a tests directory because we aren’t testing anything. Instead, we’ll put all of our JS code in app.js. We only need to look at two files for the code sample below, index.html and app.js.

HTML code

  • HTML

To enter the location, we have a basic form input. There are various div classes for displaying errors, temperature, and humidity.

JavaScript code

Let's have a look at the API call's code:

import $ from 'jquery';
import 'bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';
import './css/styles.css';
$(document).ready(function() {
$('#weatherLocation').click(function() {
const city = $('#location').val();
$('#location').val("");
let request = new XMLHttpRequest();
const url = `http://api.openweathermap.org/data/2.5/weather?q=${city}&appid=[YOUR-API-KEY-HERE]`;
request.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
const response = JSON.parse(this.responseText);
getElements(response);
}
};
request.open("GET", url, true);
request.send();
function getElements(response) {
$('.showHumidity').text(`The humidity in ${city} is ${response.main.humidity}%`);
$('.showTemp').text(`The temperature in Kelvins is ${response.main.temp} degrees.`);
}
});
});

To begin, we’ll look at our import declarations. We have a click handler that pulls a city value from a form, puts it in a variable called city, and then erases the form field $(’#location’).

val("");: This section is just for review.

The following is the first line of the new code:

let request = new XMLHttpRequest();

We create a new XMLHttpRequest object and save it in the request variable.

The name XMLHttpRequest is deceptive. These objects are not just used for XML queries. Instead, they are used to interface with servers, which is exactly what the API calls are for. As previously stated, XML is a rather widespread data format used by APIs. However, JSON is becoming increasingly popular, and XMLHttpRequest objects may be used with JSON as well as other forms of data, not just with XML.

The URL for our API call is then saved in a variable:

const url = http://api.openweathermap.org/data/2.5/weather?q=${city}&appid=[Add-Your-API-Key];

This isn't required, but it does make our code simpler to understand. For the code to operate properly, we need to add our own API key in [YOUR-API-KEY-HERE]. Because our string is a template literal with an embedded expression, ($city), the value that the user enters in the form is transmitted straight into our URL string via our city variable.

Note: We can generate an API key at the openweathermap website.

The remainder of the code is divided into the following three sections:

  • A function that monitors any changes to the XMLHttpRequest’s readyState.
  • Sending and Processing the request.
  • A callback function that will be used to display the results in the browser.

Let’s start with the function that monitors the XMLHttpRequest for changes:

request.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
const response = JSON.parse(this.responseText);
getElements(response);
}
};

onreadystatechangeis a property of ourXMLHttpRequestobject. This attribute can be set to the value of a function that performs anything we desire. We have an anonymous function (an unnamed function) set to the value of that property in the example above. 

We could even tweak the code to just track changes in the ready state:

request.onreadystatechange = function() {
console.log(this.readyState);
};

If we did, the console would show the following. We have added forward slashes to make the output display as comments.

1 // Opened
2 // Headers Received
3 // Loading
4 // Done

These numbers represent the many states in which our XMLHttpRequest object may be found. Because this is the initial state — and the readyState hasn't changed yet — we'll see 0, which corresponds to "unsent". 

Note: If we attempt this in the console, ESLint will complain about no-unused-vars. This is due to the fact that the getElements() method, which we define later in the code, is no longer in use. To avoid this, we temporarily comment ESLint. Once we’re finished, we'll restore the code to its original state.

We don't want to do anything until this.readyState is equal to 4 because the data transmission is still in progress. You'll notice that our if condition has a second condition as well. This is the this.status===200. We’ll do anything with the data if this.status === 200. Why does this happen? Is it necessary for this.status === 200 to be included in our conditional? The answer is yes. This is because the API request must be successful and the data transfer must be complete before our code analyses the data.

When the conditional is true, we execute the following code:

<html lang="en-US">
<head>
  <title>Weather</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="app.js"></script>
</head>
<body>
  <div class="container">
    <h1>Get Weather Conditions From Anywhere!</h1>
    <label for="location">Enter a location:</label>
    <input id="location" type="text">
    <button class="btn-success" id="weatherLocation">Get Current Temperature and Humidity</button>
    <div class="showErrors"></div>
    <div class="showHumidity"></div>
    <div class="showTemp"></div>
  </div>
</body>
</html>
In app.js replace "[YOUR-API-KEY-HERE]" with your openweathermap API key.

RELATED TAGS

javascript
api

CONTRIBUTOR

Shittu Olumide Ayodeji
Attributions:
  1. undefined by undefined
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?