Using Ractive.js and HTML5 Fetch API to consume REST API
The sample app here takes the city name as input and shows the corresponding weather information below it.
Get the OpenWeather API keys for FREE!!!
In order to get the JSON data from OpenWeather’s REST API, the first thing we need to do is get their free API key. The API can be called by simply passing in this app id as query parameter. That’s it!
Setting the UI container
Create an HTML5 element to be used as the front of the app. In our case, it’s
Implement responsiveness using Bootstrap
Just for implementing the responsiveness, we’ve included the Bootstrap reference. The classes
.row .col-md-6 .col-sm-12 takes care of responsiveness itself.
Set the Ractive template
After adding ractive’s link, we’ve made sure that the code in the fiddle will be Ractive-aware.
The template is in the script tag. Note that we’ve set the
The curly braces e.g.
are holding the data set inside the ractive function with e.g.
ractive.set('location', JSON.stringify(data.name) + ', ' + JSON.stringify(data.sys.country));
Set the ractive context
Ractive constructor function will be used to set the Ractive context. The parameters with their description are:
el: the element to which the front end will be rendered
template: the Ractive template
data: the data for the front end
Ractive events looks a little different than pure HTML events, e.g. on-click. They’re catched in a samilar sense as that of jQuery.
Fire the fetch request
Prepare the fetch request using the
Request constructor function and fire it using
Use localStorage to maintain recent search history
The city input is stored in the localStorage instance as an array and displayed as the
ul on click of each is the weather fetching request recap-ed.
See the whole code here.