How to call weather APIs in JavaScript?

Tue Oct 25 2022

6 min read

There are millions of APIs available on the internet. Each API is designed to achieve a specific task, for instance, payment APIs, authentication APIs, etc.

Weather APIs are one of the most popular API types. There are thousands of them available on the internet. And you can consume them to build a weather application.

In this piece, we will look at different ways to consume weather APIs in JavaScript. So without any further ado, let’s jump in!

Find Weather APIs on RapidAPI Hub

To consume weather APIs in JavaScript, we need to find them first. This is where RapidAPI comes into the picture. It provides an API Hub, i.e., RapidAPI Hub, with over 35,000+ APIs from which you can select. Google uses it to offer its official product API to consumers. The same is true for Microsoft. Go ahead and sign up there.

Once you are logged in, search for weather APIs. You will see a bunch of APIs listed as a search result.

I have already selected three weather APIs, which we will consume using JavaScript.

Go ahead and subscribe to all of these APIs. You can select the free package from the pricing plan.

Loading component...

Call Foreca Weather API in JavaScript Using fetch

Let’s do it in steps to make it simpler and easy to follow.

STEP 1

Go ahead and create an empty directory and open it in your preferred code editor. Now create an index.html file in it and write basic HTML boilerplate code.

html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Call Foreca Weather API in JavaScript</title>
</head>
<body>
<script></script>
</body>
</html>

STEP 2

On the API page of Foreca Weather API, you will see different endpoints listed on the left side. For this demonstration, we will use the Current endpoint. We will make a GET request to it.

On the right side, you will see a code snippet to call the API. You can choose the language you want from the dropdown, and the code snippet will be updated accordingly. Let’s go with (JavaScript) fetch.

Lastly, click on the Copy Code button. It will copy the code snippet to your clipboard.

STEP 3

You can write JavaScript inside the script tag. Go ahead and paste the code you copied earlier in the script tag.

html
<script>
const options = {
method: 'GET',
headers: {
'X-RapidAPI-Key': 'your-rapidapi-key',
'X-RapidAPI-Host': 'foreca-weather.p.rapidapi.com',
},
};
fetch(
'https://foreca-weather.p.rapidapi.com/current/102643743?alt=0&tempunit=C&windunit=MS&tz=Europe%2FLondon&lang=en',
options
)
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error(err));
</script>

We have created an options object and provided it to the fetch method along with the API endpoint. Then we handled the API response and error via promise-chaining.

STEP 4

Run this HTML file and open the browser console to see the API response logged there.

Call AerisWeather API in JavaScript using Axios

We will do it in steps to make it simple to understand how to call weather APIs in JavaScript.

STEP 1

We need to install Node.js to run our JavaScript file locally inside a terminal. To do this, head to Node.js website and download a stable Node.js version. Afterward, install it on your computer.

STEP 2

Create an empty directory and open it in your preferred code editor. Create an index.js file inside this directory.

Once you are done, let’s install Axios. You can do this by running the following command inside your project terminal:

sh
npm install axios

STEP 3

We will use the Current Conditions endpoint of AerisWeather API and RapidAPI Hub code snippets to call the API. Since (Node.js) Axios code snippet is selected by default, please click on Copy Code button to copy it on the clipboard.

STEP 4

Paste the code snippet in the index.js file.

js
const axios = require('axios');
const options = {
method: 'GET',
url: 'https://aerisweather1.p.rapidapi.com/observations/paris,fr',
headers: {
'X-RapidAPI-Key': 'your-rapidapi-key',
'X-RapidAPI-Host': 'aerisweather1.p.rapidapi.com',
},
};
axios
.request(options)
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.error(error);
});

We have imported axios at the top of the file so we can use it anywhere. Afterward, we defined an options object that contains the HTTP method, API endpoint, and RapidAPI headers. Lastly, we have provided this object to axios and sent the request. We have used promise-chaining to handle the API response and error.

Lastly, run the file using the following command:

sh
node index.js

You will see the API response in your project terminal.

Call Forecast API in JavaScript Using XMLHttpRequest

Let’s do it in steps, so it is easier to follow along:

STEP 1

Create an empty directory and open it in your preferred code editor. Now go ahead and create an index.html file in it and write basic HTML boilerplate code.

html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Call Foreca Weather API in JavaScript</title>
</head>
<body>
<script></script>
</body>
</html>

STEP 2

We will use the RapidApiGetHourlyForecastByLocationName API endpoint of the Forecast API. It accepts a GET request and provides weather information.

Since RapidAPI Hub already provides code snippets to call APIs, we will use it to get the code to call Forecast API using XMLHttpRequest. So go ahead and select (JavaScript) XMLHttpRequest from the dropdown menu and click on Copy Code button to copy the code snippet on your clipboard.

STEP 3

We will use the script HTML tag to write JavaScript. Go ahead and paste the code you copied above right here.

html
<script>
const data = null;
const xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener('readystatechange', function () {
if (this.readyState === this.DONE) {
console.log(this.responseText);
}
});
xhr.open('GET', 'https://aerisweather1.p.rapidapi.com/observations/paris,fr');
xhr.setRequestHeader(
'X-RapidAPI-Key',
'your-rapidapi-key'
);
xhr.setRequestHeader('X-RapidAPI-Host', 'aerisweather1.p.rapidapi.com');
xhr.send(data);
</script>

We have created a new XMLHttpRequest object and set the credentials to true. Afterward, we added an event listener to log the API response when the state changes. Then we opened a connection where we would make the GET request to the API. Then we set the request headers and send the request.

STEP 4

Run this HTML file and open the browser console to see the API response logged there.

Wrap Up

That’s all, folks! You can see how easy it is to call weather APIs in JavaScript. Click here to learn more about RapidAPI Hub from where we selected all three weather APIs.