Codementor Events

Build Your Own CLI tool to Monitor Weather

Published Feb 12, 2021Last updated Aug 10, 2021
Build Your Own CLI tool to Monitor Weather

Combining daily tasks with code is what most developers do. The need to automate things is present in every developer who does this out of passion. Even if the tasks aren’t very time consuming when done manually, if they can be automated then why not automate them?

One such task or routine is reading weather forecasts. Therefore, I thought to create a CLI tool that will show me exactly what I'm interested in for my hometown.

This is how I did it and how you can build it yourself as well.

Step 1: Acquiring Weather Data

The first steps are to decide what indexes you want to show, and find a free weather API with your desired features.

For my own case, I knew I wanted some basic information such as temperature, humidity, wind speed and a general description of the weather conditions, and then extend the functionality to other data layers, such as air quality. A data provider that meets these requirements is the ClimaCell Weather API. They have a free plan that provides an API Key to be used with a limit of 1000 calls / per day.

ClimaCell API provides weather data through a get request at the following URL:

https://data.climacell.co/v4/timelines?location=LAT%2CLONG&fields=FIELD_NAME&timesteps=TIME_STEP&apiKey=YOUR_API_KEY

  • LAT and LONG are the coordinates of the location for which you want to get the weather data,
  • timesteps is used to specify the time frame of the weather samples: realtime, hourly, daily and so on,
  • apiKey is your API Key,
  • fields is an array with the fields you want to get data for; you can find a list with them in their documentation.

Therefore, to get the temperature, humidity, wind speed, and a general description of the weather in my home town, my URL look like this:

https://data.climacell.co/v4/timelines?location=45.6427%2C25.5887&fields=temperature&fields=humidity&fields=windSpeed&timesteps=1m&fields=weatherCode&apikey=API_KEY

To get the current weather data we can use the value 1m for timesteps.

If you want to get the same data for your city, do a quick google search with YOUR_CITY_NAME coordinates, and the first value that comes up (marked with °N ) will be the latitude, and the second one (marked with °E), will be the longitude.

Then just replace the value in front of %2C with the found latitude and the value after %2C with longitude. Don’t forget to also replace API_KEY with the value of your secret key.

Once you have the URL created, open a new tab and paste it in the address bar to validate it. This will send a GET request and retrieve the data. If the URL is correct then you should see the following response:

You can use a browser extension to clean up the code in this format. I’m using JSONView.

The response has a JSON format and it includes the weather data for the next 360 minutes.

By default it’s using the International System of Units. if you want to retrieve the data in United States customary units, then all you have to do it append to the URL you are using the value &units=imperial for US customary units or the default value &units=metric for the International System of Units.

The values that we are interested in for a real-time weather report can are inside data.timelines[0].intervals[0].values. Basically, those are the values that we would want to extract.

Step 2: Project Setup

Now we need a programming language to automate this process. For this article and project, I'm going to use Node JS.

To setup the project we need to run this command in the terminal:

npm init -y && npm i commander node-fetch

This composed command will first run npm init -y which will create a new package.json file. Then, npm i commander node-fetch will install the required dependencies: commander to build a CLI behavior and node-fetch to send the GET request. Next, in a new .js file, add these dependencies and your API key.

At this point, the project structure should look like this:

To finish this setup we just need to add the weather codes that will be used to map to a general weather description.

You can get them from their documentation under weatherCode field and then paste them into a new file, named weather-codes.js

Lastly, to import this codes, update index.js with the following line:

const { WEATHER_CODES } = require("./weather-codes");

Code

Code

Step 3: Get the Weather Data

Create a function that based on a given latitude and longitude, will make a GET request to the URL we previously used, and return the data.

This function will return the exact values we saw before but in a more readable form, including the unit of measurement as well.

Code

Code

We used a destructuring assignment to get the data and values.

To make the CLI took more general, I’ve decided to manually supply the latitude and longitude when calling the script, therefore it can be used for any location and not a hard coded one.
That latitude and longitude will be then sent as arguments to this function getWeatherData()

Step 4: CLI behavior

commander will be used to implement a CLI behavior by analyzing the received arguments

This NodeJS module can be used in the following form:

RAW

We start by mentioning a version and then defining commands, along with the options that can be used to run these commands.

Then we supply the code we want to execute as a callback. In our case, get the supplied latitude and longitude, get the formatted weather data, and then display it in the console.

Lastly we need to call program.parse(process.argv) in order to parse the arguments.

Step 5: Run the Program

If we run node index.js help, where help is a predefined command, we should see the following output:

In the Commands section, we have help, the one that we just executed and weather, the command that we defined.

We can be more specific and run node index help weather or node index.js weather -h:

This will show the manual for the weather command.

Based on this manual, if I want to get the weather data for my hometown, I have to run the following command:

Wrap up

You can take this small application even further and publish it on npm so you can install it as a global package and execute it using the package name instead of the file path. Just be sure not to publish your API key as well. You can also improve it and add other data layers as well, like a command for air quality or even precipitation.

On top of that, the new API updates from ClimaCell can allow you to scale even more. If you don't want to check the weather each time, you can create events that will monitor the weather and trigger alerts based on custom rules. You can also use the application to plan your future travels. By adding the Routes API, you can get realtime weather data along your travel path.

A good weather API will allow you to do all this and even more. With a rich collection of data fields made available through an easy to use API, the sky is the limit.

Cover Photo by engin akyurt on Unsplash

Discover and read more posts from Josh Robins
get started
post commentsBe the first to share your opinion
Show more replies