Monitoring weather data is not rocket science. Nowadays, with just a simple Google search, you can see what the weather’s like in Antarctica just as easily as you would in Boston. 

Finding short weather data about an area of interest is something anyone with internet access can do. And you have a multitude of sources from which you can choose. The problem arises when you want a more personalized weather forecast with fields that not everyone will have a use for, such as barometric pressure or wind direction. 

simple weather app Tomorrow.io

This is a problem I’ve often faced. In addition, better control over this data would also be nice. For example, email alerts or a web application that can be installed on your phone or even a map integration.

As developers, we have an advantage in this situation, given that we can code our own solutions. 

In this article, we will see how we can use a weather API and a few lines of code to acquire the weather forecast for the next 7 days.

How to Code It

First and foremost, we need a weather data provider. The Tomorrow.io Weather API offers a variety of information we can collect about the weather.

The first step is to create a free Tomorrow.io account and obtain a private key, which will be used to communicate with the API.

www.tomorrow.io weather api key

As soon as we have this API key, we can get started.

Base Configuration

The first step consists of the basic setup for the project we want to develop. Because we can develop several solutions that can include front-end applications, back-end applications or just simple scripts, the configuration will be different for each case.

In this article we will focus mainly on how to obtain the weather data and at the end, we will see briefly what steps we need to follow depending on the solution we want to develop.

For coding, I choose NodeJS, so regarding where you want to deploy your application, the code will mostly be the same and JavaScript-based.

To initiate our NodeJS project, we simply need to run the next commands in the terminal (assuming you have NodeJS installed on your machine). 

npm init -y && npm i node-fetch

node fetch

These two commands will first create a new package.json file that will be used to handle the dependencies we need. After the npm init -y command finishes, it will run npm i node-fetch, which will install the node-fetch dependency that we will use to send requests to the Tomorrow.io API.

Finally, let’s create a main file called index.js, and the folder structure of our project should be as follows:

weather app folder structure

Folder Structure

 

Variables and Helpers

Once we have this project structure and the package node-fetch installed, we can continue and start writing some code. 

At the beginning, we need to define some global constants that we will use throughout the project.

const fetch = require("node-fetch");

// * globals
const LAT = 37.7749;
const LONG = -122.4194;
const WEATHER_FIELDS = ["weather_code", "temp", "wind_speed", "humidity"];
const CC_KEY = "your_api_key_here";

LAT and LONG are the geographical coordinates of the address for which we want to see the weather data. We will store our private key provided by Tomorrow.io in the variable CC_KEY.  

WEATHER_FIELDS is an array with all the core information we want to take from this API.

Just make sure that the field that you want to use is available for the forecast you want to receive. 

In our case, we are interested in a daily forecast. Whatever field we want to use, we must ensure that it has the Daily box checked.

data fields weather api

Fields available

I created a helper function which we’ll use in this program to make things easier when we write the code that will call the API. This function will simply format an URL and append the properties you want as query parameters.

function queryBuilder(request, options) {
  request += "?";
  Object.keys(options).forEach((key) => {
    if (typeof options[key] === "number" || typeof options[key] === "string") {
      if (request[request.length - 1] !== "?") {
        request += "&";
      }
      request += `${key}=${options[key]}`;
    } else if (Array.isArray(options[key])) {
      options[key].forEach((e) => {
        if (typeof e === "number" || typeof e === "string") {
          if (request[request.length - 1] !== "?") {
            request += "&";
          }
          request += `${key}=${e}`;
        }
      });
    }
  });
  return request;
}

To better understand this, check the next example.

If we call this function with these parameters:

 queryBuilder("https://www.youtube.com/results", {
   search_query: "abba",

It will create the following URL: https://www.youtube.com/results?search_query=abba

Get the Weather Data

To get the weather data that we want, all we need to do is to create a GET request to Tomorrow.io. When making this request, we have to specify the following query parameters: latitude and longitude, our API key, and the fields we want to retrieve.

// * get weather data
async function getWeatherData() {
const url = queryBuilder(
"https://api.www.tomorrow.io/v3/weather/forecast/daily",
{
lat: LAT,
lon: LONG,
unit_system: "si",
fields: WEATHER_FIELDS,
apikey: CC_KEY,
}
);

const res = await fetch(url);
const data = await res.json();
return data;
}

(async function () {
const weatherData = await getWeatherData();
const next7Days = weatherData.slice(0, 7);
})();

The function getWeatherData() will return the daily forecast for the next 15 days as an array.

If we don’t want to get the data in the International System of Units, we can change the value of the property unit_system from si to us. This will convert the data in United States Customary units.

Further Directions

What we have seen so far is the basis for the application we want to create in the future.

A first direction is to create a web application where we can see this data.  

In this case, the benefit of using NodeJS is obvious, because we can take the entire code and run it in the browser. All we need to do is to remove the first line const fetch = require(“node-fetch”); due to the fact that here fetch is a browser API and it’s already available for use.

We can use a Geocoding service to create a web application. Based on a given address, we can create cards with the weather forecast for the next several days. 

Or we can create a live map with the Google Map API or OpenLayer, and display weather data based on this map, just like Tomorrow.io’s HyperCast software does.

Another benefit of a web app is that we can easily convert it to a PWA and have it installed on mobile phones. 

Another possible direction is to create an email notifier for when the weather data or the air quality breaks certain thresholds. Besides weather data, Tomorrow.io offers a data layer for Air Quality as well. Using the same API, we can have a weather forecast and an air quality forecast.

It’s a bit more difficult to create an email notifier than a UI, but not impossible. We can use Nodemailer for this, a NodeJS package through which we can send emails.

If you have a private email server then you can use it as a transporter for your emails. If not, you can use Gmail, but you need to specifically set a flag in which you enable less-secure apps to use your Gmail account.

Conclusion

The possibilities are endless. The starting point is knowing how to call this kind of API to acquire the weather data of interest. After that, the world’s your oyster when it comes to what you can do with it. 

 

Just keep in mind that these APIs come with a rate limit, depending on your plan. In Tomorrow.io’s case, the free plan allows developers to do up to 1000 calls/day, but no more than 100 calls/hour. Make sure that your plan is enough for you based on the application you want to build.