This course will be retired on September 1, 2022. We recommend "Node.js Basics" for up-to-date content.
Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
In this video I'll show you how I retrieved information from a weather API.
Documentation
- require
- process.argv
- https.get
- Stream Event: 'data'
- Stream Event: 'end'
- String.replace()
- Array.slice()
OpenWeatherMap API Solution Code
The OpenWeatherMap API works a little differently than the API shown in the video:
- You can't pass it a city/state combination, but you can either pass it a city name or a zip code
- You need to specify the units format as an additional query string parameter in order to get the temperature in fahrenheit
- Temperature is available in Fahrenheit, Celsius and Kelvin units
- For temperature in Fahrenheit use
units=imperial
- For temperature in Celsius use
units=metric
- Temperature in Kelvin is used by default, no need to use units parameter in API call
Here's an overview of the differences from the code shown in the video:
-
app.js
- Removed the code that replaces spaces with underscores
-
weather.js
- Switched to using the
querystring.stringify()
method to URL encode a parameters object - Added a check to see if the provided query is a number or not in order to determine which API endpoint to use
- Switched to using the
Here's the code:
app.js
const weather = require('./weather');
const query = process.argv.slice(2).join(' ');
//query: 90201
//query: Los Angeles
weather.get(query);
weather.js
const https = require('https');
const querystring = require('querystring');
const api = require('./api.json');
// Print out temp details
// Print out error message
function get(query) {
const parameters = {
APPID: api.key,
units: 'imperial'
};
const zipCode = parseInt(query);
if (!isNaN(zipCode)) {
parameters.zip = zipCode + ',us';
} else {
parameters.q = query + ',us';
}
const url = `https://api.openweathermap.org/data/2.5/weather?${querystring.stringify(parameters)}`;
console.log(url);
const request = https.get(url, response => {
let body = "";
// Read the data
response.on('data', chunk => {
body += chunk;
});
response.on('end', () => {
console.log(body);
//Parse data
//Print the data
});
});
}
module.exports.get = get;
//TODO: Handle any errors
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up