Did you enjoy our Getting started with World Weather Online API using PHP article? This time we’re going to show you how to use our API with the ever popular NodeJS.

Just like the last post, we need an API key to begin…

Getting your API key

Your API key is a unique randomly generated key which identifies your or your applications account. You can get your own API key by registering with World Weather Online. Your API key will look something like this:

a7e124b57d3e3d3671960ddcbe467 (note: This is not an actual key)

Getting up and running

To get up and running quickly, we’re going to keep things fairly simple and focus on putting all code in one file to create a simple five day visual weather forecast.

Firstly we need to set up Node and the required packages. You can download and install Node.js here, then we will setup our package.json file:

// file: package.json { "name": "wwo-api-with-node", "version": "1.0.0", "description": "A simple five day weather forecast using the WWO API", "dependencies": { "express": "4.2.x", "request": "^2.53.0" }, "private": true, "license": "MIT" }

You can learn more about setting up your package.json file using this reference. Now we’ll run npm install in our terminal in the project directory to install the express middleware.

Next create a new javascript file called app.js in your project folder, we’ll create some variables to use later on in our application and setup a quick handler to show a Hello message when we go to our app.

// file: app.js var express = require('express'); var app = express(); var request = require('request'); var apiKey = 'a7e124b57d3e3d3671960ddcbe467'; // our fake API key from above. app.get('/', function (req, res) { res.send('Hello World!'); }); var server = app.listen(3000, function () { var host = server.address().address; var port = server.address().port; console.log('Your app listening at https://%s:%s', host, port); });

If you run node app.js in your terminal window now you should see Hello World!

Now we need to start looking at how the API actually works. The API allows you to make requests using a GET request, which means we can pass information to the API by adding parameters to the URL.

Therefore to tell the API that we want information about the weather in New York, we could add ?q=new+york to the end of the URL. The API is quite flexible when it comes to searching, you can use city and town name, zip/postcodes, lat/lon co-ordinates or even an IP address.

The API accepts a number of parameters so that we can specify exactly what we need and below I have listed the parameters that are required for each request with a small explanation of each.

For a full list of the parameters visit API Documentation.

Required API Request Parameters

Parameter Description Required Values q Location Required See note below num_of_days Number of days of forecast Required, except for monthly average Integer. Example: num_of_days=2 key The API key Required Provided when registering your application

So to make our request, our URL will be something like:

https://api.worldweatheronline.com/free/v2/weather.ashx?q=new+york&num_of_days=5&key=a7e124b57d3e3d3671960ddcbe467&tp=24&format=json

I’ve added two optional parameters here, one of which tp is the time period. We used 24 to get a 24hr average and we also set the format parameter to JSON.

Making this request with node.js

To make this request with node.js we are going to use the express module we got a reference to earlier, and with this we’ll set a simple function that will make the request, receive the response and parse it for us.

We now going to enhance the app.get code that we used above to make the request to the API, parse the response and build a visual HTML table to display the results.

// file: app.js var requestUrl = 'https://api.worldweatheronline.com/free/v2/weather.ashx?q=new+york&num_of_days=5&key=a7e124b57d3e3d3671960ddcbe467&tp=24&format=json'; function dayOfWeekAsString(dayIndex) { return ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"][dayIndex]; } app.get('/', function (req, res) { request(requestUrl, function (error, response, body) { if (!error && response.statusCode == 200) { // parse the json result var result = JSON.parse(body); // generate a HTML table var html = '<table style="font-size: 10px; font-family: Arial, Helvetica, sans-serif">'; // loop through each row for (var i = 0; i < 3; i++) { html += "<tr>"; result.data.weather.forEach(function(weather) { html += "<td>"; switch (i) { case 0: html += dayOfWeekAsString(new Date(weather.date).getDay()); break; case 1: html += weather.hourly[0].weatherDesc[0].value; break; case 2: var imgSrc = weather.hourly[0].weatherIconUrl[0].value; html += '<img src="'+ imgSrc + '" alt="" />'; break; } html += "</td>"; }); html += "</tr>"; } res.send(html); } else { console.log(error, response.statusCode, body); } res.end(""); }); });

In the line var result = JSON.parse(body); we get the vast amount of information returned from our API but we’ve only displayed a small portion of it for the purposes of this example.

With these changes in place, restart your node application by running node app.js again, you should be output similar to the below image.