Awesome, now that we have our API Key we can start creating our app!

Step 2: Setting up the project

Create an empty directory named node-weather and run:

npm init

2. Fill out the required information to initialize our project.

Here’s what my package.json file looked like after initializing my project. Note: Yours may look slightly different, that’s OK.

3. Create a file named index.js — this file will house the code for our application.

Now that we have all the puzzle pieces, we can start building!

Making the API call

To make our API call, we’ll be using a popular npm module called request. request has millions of downloads and is a module that simplifies the code needed to make an http request in node.

Install request by running:

npm install request --save

As I said, request is pretty easy to use. We just need to pass in our target url, and request returns a callback function. Our starter code looks like this:

const request = require('request'); request(url, function (err, response, body) {

if(err){

console.log('error:', error);

} else {

console.log('body:', body);

}

});

Lets break this code down:

We require the request package We pass in a url, and request returns a callback function with three arguments: err , response , and body . We check for an error in our request. If there is one, we log the error and are done. If there is no error, we log the entire contents of the response body.

Awesome, so what is the url we’re making the request to?

By reading the OpenWeatherMap Documentation, we are able to determine that this is url we should make our requests to: http://api.openweathermap.org/data/2.5/weather The URL also has two required query parameters. Query parameters are key/value pairs that allow us to pass in data to a URL. In this instance we need to include the city we’re searching for, and our API Key.

Here’s what the code will look like:



let city = 'portland';

let url = ` let apiKey = '****************************';let city = 'portland';let url = ` http://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}`

We’ve done 3 things above:

Create a variable named apiKey and assigned it the string value of our API Key (note: your api key will not be ‘***’s) Create a city and assigned it a string value of the city we’d like to test with Create a variable named url and assigned it the OpenWeatherMap url with our two required query parameters. Notice that query params start with a ? question mark. They are then indicated with key/value pairs separated by an = equal sign. Different key/value pairs are separated with an & ampersand.

At this point, if we put everything together, here’s what our code should look like:

We can now run our code in the console by typing:

node index.js // the following is returned:

body: {"coord":{"lon":-122.68,"lat":45.52},"weather": [{"id":801,"main":"Clouds","description":"few clouds","icon":"02d"}],"base":"stations","main":{"temp":302.15,"pressure":1014,"humidity":51,"temp_min":301.15,"temp_max":303.15},"visibility":16093,"wind":{"speed":2.6,"deg":320},"clouds":{"all":20},"dt":1497905580,"sys":{"type":1,"id":2274,"message":0.0042,"country":"US","sunrise":1497874905,"sunset":1497931383},"id":5746545,"name":"Portland","cod":200}

It works! As you can see, we’ve successfully made a request to OpenWeatherMap’s API and gotten the following data back. There’s lots of good information scattered throughout: I see temperature, humidity, and wind speed just to name a few.

IMPORTANT: You would never have your API key exposed in your code like this. For brevity, I’m leaving it in the open like this. In future tutorials I will show you how to hide your API key using environment variables. For now, just know that it is not standard to have your API key exposed like this.

Cleaning up our response

The application isn’t really helpful as is. The jumbled mess of data that’s returned is just annoying. Lets clean everything up.

The first thing we need to do is convert the jumbled text that’s returned (called JSON) into a JavaScript Object. (JavaScript Object Notation) is a way to store information in an organized and easy to access manner — and it looks like a JavaScript Object, but if you noticed, there are some extra quotation marks involved.

We can make this conversion with one line of code:

let weather = JSON.parse(body)

Now that we have a JavaScript object, we can access data within the object with dot or bracket notation. Below, we construct a message string by accessing data within our weather object:

let message = `It's ${weather.main.temp} degrees in

${weather.name}!`;

console.log(message);

If we were to run our app at this point, we’d get:

node index.js // It's 300.4 degrees in Portland

Wait. What?

We didn’t do anything wrong. What’s happening is OpenWeatherMap actually defaults its temperature to Kelvin. So we need to add another query parameter. If you use Celsius you’d add: units=metric and if you use Fahrenheit you’d use units=imperial .

Now if we run:

node index.js // It's 70.1 degrees in Portland

Here’s what our code should look like at this point:

Adding in interactivity

Our app is still boring. We can only access the weather for Portland, Oregon. Lets add some interactivity. For this, we’ll use yargs. Yargs is a pirate themed interactive command line interface tool. Or more simply put, it allows us to define variables from the command line.

Install yargs with:

npm install yargs --save

Yargs works by exposing any variables we use in the console onto the argv object. We set up and access this object like so:

const argv = require('yargs').argv;

We’ll use the flag of c for city:

Lets have our city variable equal either argv.c OR if no variable is input, we’ll have a default city value of Portland :

let city = argv.c || 'portland';

Now, to run the app, instead of just saying:

node index.js

We need to pass in a variable named c like this:

node index.js -c Boston // It's 85 degrees in Boston

We use a flag to indicate we’re passing in the variable. Since we set up our variable to be the letter c we pass in our variable with -c . After a space, we can use any city name we’d like!

node index.js -c Anchorage // It's 47 degrees in Anchorage

At this point, here’s what our code looks like:

You did it!

And that’s how you build a weather application with Node.js! What do you want to learn? Tweet me @BrandonMorelli to let me know and I’ll cover it in Part 2 of this series! Also, I publish a few articles and tutorials each week, please consider entering your email here if you’d like to be added to my once-weekly email list.