Agriculture is one of the riskiest industries out there. A recent study from the UK has highlighted the high rate of fatalities among farm workers, for example, with the elderly being most affected by this problem.  

The accidents came in all kind of forms, including workplace safety or heat strokes triggered by unfavourable weather conditions.

Even if the weather conditions are not responsible for all the accidents, they still play an important role in increasing this number of fatalities. Therefore, monitoring weather conditions is important and can help create a safer, more efficient, workplace.

For example, one might use weather data to schedule working hours for workers based on weather conditions and their ages, or one might search for the best time for certain tasks that have a higher risk under extreme temperatures.

Another use case is for a farmer to adapt to weather conditions given by the current situation and take additional farm management practices to minimize crop losses. Therefore, accurate information regarding the weather is important so that farm activities can be planned without adverse effects.

Being aware of forecasted weather data and real-time weather conditions as well as other parameters like air and dew temperature, precipitation, and humidity is the best way to protect crops and secure a high and healthy yield. Extreme weather such as dryness, floods, or frost can cause instant plant stress, thus leading to failed production and increased costs.

That’s why accurate weather forecasts can help the farming industry manage and ensure the quality of the crop production. The possibilities for actually using this type of data are endless, but how do we get this information?

To obtain weather data we can combine programming with the use of a weather API. Here’s how to do it. 

Choose a Weather Data Provider 

The first step is to find an external provider that collects weather data and makes it public via an API.

Even if there are several weather data providers, the one that suits our case is www.tomorrow.io. The advantage it has is that it is a MicroWeather API. Thus, the monitored areas have a much smaller radius, and the data is way more accurate. In addition, other monitoring tools are used in addition to the classic ones.

To use this API you need to create a free account on Tomorrow.io and navigate to your dashboard in order to obtain the private key. This key will be used by Tomorrow.io for identification.

With this API key, you can make up to 100 calls per hour and up to 1000 calls per day. This should be more than enough.

The Code

Now that we have a data provider and an API key we can start writing some code.

Setup

We will use JavaScript as a programming language and to be more precisely NodeJS. So the first step is to install this software on your computer.

To see if it’s installed correctly you can open Command Prompt and type node -v. This command should output the current version of NodeJS.

Once it’s installed we can set up the project. In a new folder, let’s create a new file named index.js and run this commands inside Command Prompt:

After this, the folder structure should be the following:

npm stands for node package manager and is used to manage public or private packages (libraries). 

Next, open index.js and write the following code:

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

const API_KEY = "";

Here we imported the package we just installed along with the package fs which is available by default.

In the variable API_KEY write your API key in quotation marks.

Get the Weather Data

We receive weather data from Tomorrow.io by making different GET requests to some certain endpoints and by sending some special fields.

For example, a GET request to this URL:

https://api.www.tomorrow.io/v3/weather/realtime?lat=37.9838&lon=23.7275&fields=humidity&fields=temp&apikey=your_api_key

This will return the current Humidity and the Temperature for Athens, Greece.

{         "lat": 37.9838,         "lon": 23.7275,         "temp": {                 "value": 26.88,                 "units": "C"         },         "humidity": {                 "value": 47.94,                 "units": "%"         },         "observation_time": {                 "value": "2020-08-14T06:50:03.140Z"         } }

If we want to get the Wind speed as well, all we need to do it to append this string &fields=wind_speed to the URL above.

You can replace your_api_key with your actual Tomorrow.io Key and paste this URL in a new tab.

This example was for realtime weather forecast. This data provider offers multiple data layers, including nowcasting, hourly forecast and so on. You can see the full list this layers including all the available files on their reference page.

For us, to collect this data using code, we need to do as well a get request to a URL just like the one above.

To avoid scenarios where we have a long URL from which we can’t distinguish anything, like this one for example:

https://api.www.tomorrow.io/v3/weather/forecast/daily?lat=23.7275&lon=37.9838&unit_system=si&fields=humidity&fields=wind_speed&fields=temp&fields=weather_code&fields=baro_pressure&fields=precipitation&fields=precipitation_probability&fields=precipitation_accumulation&fields=visibility&apikey=your_api_key

We are going to use a help function to have this URL built for us.

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;
}

So take this function as it is and append it in index.js.

With the help of this function, we can write something like this instead of the very long URL from before:

async function getWeatherData(lon, lat, apiKey) {
const fields = [
"humidity",
"wind_speed",
"temp",
"weather_code",
"baro_pressure",
"precipitation",
"precipitation_probability",
"precipitation_accumulation",
"visibility",
];

const url = queryBuilder(
"https://api.www.tomorrow.io/v3/weather/forecast/daily",
{
lat,
lon,
unit_system: "si",
fields: fields,
apikey: apiKey,
}
);

const Tomorrow.ioRes = await fetch(url);
const Tomorrow.ioData = await Tomorrow.ioRes.json();

return Tomorrow.ioData;
}

getWeatherData() is a function that receives as parameters the geographical coordinates for a given location and an API key.  Then it builds the corresponding URL for Tomorrow.io with some predefined fields and sends the GET request.

If you want to get more data, including things like the time the sun rises, all you need to do is add another entry in fields array, for example sunrise.

Lastly, to get this weather data, we can call this function and have the output printed in a file.

The data format is JSON, thus the file name has the extension .json, but it can be printed in any file, because it’s just simple text.
To run this code, open the terminal in your project’s folder and simply run node index.js.
After this you should see that a file data.json was created. 

Conclusion

Weather conditions affect all the activities we do. With the right data, the best decisions can be made so as to build a work environment that is as efficient as possible but also as safe as possible.
With the information above, you now know how you can collect the weather data needed for your situation and it is up to you how you want to use it.