You don’t need to be an API guru to interact with the AerisWeather API. In fact, we’ve recently launched a JavaScript SDK that simplifies building your API queries and handling the responses. By the end of this post you’ll see just how to easy it is to play with our API.
We’re all about choices with the latest JavaScript SDK. Did you want to access weather data via NodeJS or browser-based JavaScript? Either way, we will have you covered. Both options have their own benefits, but it will be up to you to determine which implementation method best suits your use case. For this exercise I’ll use the browser-based method.
Go ahead and sign up for the free developer trial. If you’ve already done this you are one step ahead — nicely done. You’ll need your Client ID and Client Secret to complete this tutorial. A couple of other topics you may need to brush up on before we dive any deeper:
I’m guessing the first 2 were known prerequisites when you read the title, but you’ll notice later on there are some Bootstrap references. Have no fear, you don’t need to know any Bootstrap to use the JavaScript SDK. I just decided to use it for the example that we’re about to step through below.
I’ve decided we need to have a page that displays a simple 5 day forecast for Minneapolis, MN. It should look something like this when we’re all done:
Should be fairly simple, let’s start with the scripts and CSS that we will use and put them in our <head> tag.
1 2 3 4 5 6 |
<head> <meta charset="UTF-8"> <title>Aeris JavaScript Forecast</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <script defer src="<a href="https://cdn.aerisapi.com/sdk/js/latest/aerisweather.min.js">https://cdn.aerisapi.com/sdk/js/latest/aerisweather.min.js</a>"></script> </head> |
As you can see we are only loading Bootstrap’s CSS file and, of course, the AerisWeather JavaScript SDK script. You’ll notice I included the attribute defer in the script tag. We’re doing this because it allows us to load the script asynchronously so we can render HTML without waiting for the script to complete downloading and executing. This is simply to improve performance and load times for the user. Feel free to check out this detailed article for more information. Alternatively, you could load the script at the bottom of the page just above the closing </body> tag to accomplish the same goal. Moving onto the <body> , let’s add our page title and a place to insert the forecast details once we get them.
1 2 3 4 5 6 7 8 |
<div class="container" id="header" style="margin-bottom: 25px;"> <h1 class="display-3">Aeris JavaScript SDK Forecast</h1> </div> <div class="container" id="forecast-body"> <h3 class="display-6" id="location"></h3> <div class="row" id="forecast-items"></div> </div> |
Now, AerisWeather JavaScript SDK Forecast is our page title and we have a target element to put the location name and forecast details. Your page should look like this so far:
First things first, we need to instantiate the library with our client credentials:
1 |
const aeris = new AerisWeather('CLIENT_ID', 'CLIENT_SECRET'); |
Now we can have some fun and start using the AerisWeather JavaScript SDK:
1 2 3 4 |
const loc = 'minneapolis,mn'; const forecastRequest = aeris.api().endpoint('forecasts').place(loc).limit(5).get(); const placesRequest = aeris.api().endpoint('places').place(loc).get(); |
You’ll notice I initially declared the loc variable for Minneapolis which was passed to my placesRequest and forecastRequest. Each request was built with the previously instantiated aeris variable, which is an instance of AerisWeather, while chaining various methods starting with api() to create the full query. Let’s break down each request:
Following aeris.api(), we used the endpoint() method which takes a string argument that correlates with one of the supported Weather API endpoints. Now that we know we’re using the forecasts endpoint, we can use the endpoints parameters to further specify what we’re looking for. We know we want forecast data for Minneapolis and we know we only want 5 days worth. Therefore, we can then chain the place() method, which takes a string that represents your location (or in this case, the loc variable), and the limit() method, which takes an integer to define the number of days we want. Finally, we can apply the get() method which will trigger the library to actually perform the HTTP request and save the results as a Promise in our forecastRequest variable.
Very similar to the forecast setup, we need to define the endpoint (places) and tell our query where to search. That’s all we need for this request, so I’ll cap it off with the get() method as we did with the forecast.
Believe it or not, we’re done using the JavaScript SDK since we were able to get exactly what we wanted with the previous code snippets – weather data!
In the forecast request, I briefly mentioned the the results would be stored as a Promise. This is handy because it allows us to execute code after the completion of an asynchronous operation. Since we’re working with two promises, we can use the ever-so-handy Promise.all() method to take care of both requests and then start adding content to the page.
1 2 3 4 5 6 7 8 9 10 11 |
const weatherResults = Promise.all([forecastRequest, placesRequest]); weatherResults .then((apiResults) => { const forecastsResults = apiResults[0].data; const placesResults = apiResults[1].data; document.getElementById('location').innerHTML = formatPlaceName(placesResults); renderForecastDays(forecastsResults[0].periods); }); |
Once the results are defined you can see I’m calling two separate functions: formatPlaceName and renderForecastDays. I’d like to think both of these function names are self-describing, but just in case they’re not here’s what they’re doing:
This function will take the results from places query and use either the state name or country name to display the location. I wanted to make sure if I were to ever use this page again for a location that doesn’t support states / provinces, we wouldn’t have to add logic later on.
1 2 3 |
function formatPlaceName(obj) { const stateOrCountry = (obj.place.state) ? obj.place.state : obj.place.country; return <pre class="inline:true decode:1 " >${obj.place.name}, ${stateOrCountry} |
;
}
This function will take each period from the forecast request and inject the details into our page. Here you’ll see me doing a couple things:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
function renderForecastDays(periods) { periods.reverse(); const weekdayNames = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ]; periods.forEach(period => { const dayName = weekdayNames[new Date(period.dateTimeISO).getDay()]; const iconSrc = <pre class="inline:true decode:1 " >https://cdn.aerisapi.com/wxblox/icons/${period.icon || 'na.png'} |
;
const maxTempF = period.maxTempF || ‘N/A’;
const minTempF = period.minTempF || ‘N/A’;
const weather = period.weatherPrimary || ‘N/A’;
const template = ( <div class="card" style="width: 20%"> <div class="card-body"> <h4 class="card-title text-center">${dayName}</h4> <p><img class="card-img mx-auto d-block" style="max-width: 100px;" src="${iconSrc}"></p> <h6 class="card-title text-center">${weather}</h6> <p class="card-text text-center">High: ${maxTempF} Low: ${minTempF}</p> </div> </div>);
document.getElementById(‘forecast-items’).insertAdjacentHTML(‘afterbegin’, template);
});
}
The final product should look something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Aeris JavaScript Forecast</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <script defer src="https://cdn.aerisapi.com/sdk/js/latest/aerisweather.min.js"></script> </head> <body> <div class="container" id="header" style="margin-bottom: 25px;"> <h1 class="display-3">Aeris JavaScript SDK Forecast</h1> </div> <div class="container" id="forecast-body"> <h3 class="display-6" id="location"></h3> <div class="row" id="forecast-items"></div> </div> <script> window.onload = function() { const aeris = new AerisWeather('CLIENT_ID', 'CLIENT_SECRET'); const loc = 'minneapolis,mn'; const forecastRequest = aeris.api().endpoint('forecasts').place(loc).limit(5).get(); const placesRequest = aeris.api().endpoint('places').place(loc).get(); const weatherResults = Promise.all([forecastRequest, placesRequest]); weatherResults .then((apiResults) => { const forecastsResults = apiResults[0].data; const placesResults = apiResults[1].data; document.getElementById('location').innerHTML = formatPlaceName(placesResults); renderForecastDays(forecastsResults[0].periods); }); function formatPlaceName(obj) { const stateOrCountry = (obj.place.state) ? obj.place.state : obj.place.country; return <pre class="inline:true decode:1 " >${obj.place.name}, ${stateOrCountry} |
;
}
function renderForecastDays(periods) {
periods.reverse();
const weekdayNames = [
‘Sunday’,
‘Monday’,
‘Tuesday’,
‘Wednesday’,
‘Thursday’,
‘Friday’,
‘Saturday’
];
periods.forEach(period => {
const dayName = weekdayNames[new Date(period.dateTimeISO).getDay()];
const iconSrc =
https://cdn.aerisapi.com/wxblox/icons/${period.icon || 'na.png'};
const maxTempF = period.maxTempF || ‘N/A’;
const minTempF = period.minTempF || ‘N/A’;
const weather = period.weatherPrimary || ‘N/A’;
const template = ( <div class="card" style="width: 20%"> <div class="card-body"> <h4 class="card-title text-center">${dayName}</h4> <p><img class="card-img mx-auto d-block" style="max-width: 100px;" src="${iconSrc}"></p> <h6 class="card-title text-center">${weather}</h6> <p class="card-text text-center">High: ${maxTempF} Low: ${minTempF}</p> </div> </div>);
document.getElementById(‘forecast-items’).insertAdjacentHTML(‘afterbegin’, template);
});
}
}
</script>
</body>
</html>
I wrapped our entire code block around a window.onload() function. This is required since we used the defer attribute to load our script as we did not the code on this page to start executing until the library script was fully loaded and executed.
Now that we’ve put all the pieces together, you should have a working page that shows you the forecast for Minneapolis (or whatever city you chose). Here is the finished product:
Hopefully this brief introduction was able to inspire you to make your own web application. We’d love to see what you can do with the new AerisWeather JavaScript SDK!
2 Comments
[…] recently published a blog detailing how users can fetch data from the API using the new JavaScript SDK. This time we’ll spend a few minutes diving into the SDK’s […]
[…] like the fetching data and static maps posts related to our JavaScript SDK, we will need to get our feet set with a few […]