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.
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
.
To enter the location, we have a basic form input. There are various div
classes for displaying errors, temperature, and humidity.
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:
XMLHttpRequest
’s readyState
.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);}};
onreadystatechange
is a property of ourXMLHttpRequest
object. 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 // Opened2 // Headers Received3 // Loading4 // Done
<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 youropenweathermap
API key.