Using Ractive.js and HTML5 Fetch API to consume REST APIby@xameeramir
914 reads
914 reads

Using Ractive.js and HTML5 Fetch API to consume REST API

by Zameer AnsariMarch 28th, 2017
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Recently I was given a task to consume an <a href="" target="_blank">open</a> rest based API from <a href="" target="_blank">Open Weather</a> using <a href="" target="_blank">Ractive.js</a> and <a href="" target="_blank">HTML5’s Fetch API</a>

Companies Mentioned

Mention Thumbnail
Mention Thumbnail
featured image - Using Ractive.js and HTML5 Fetch API to consume REST API
Zameer Ansari HackerNoon profile picture

Recently I was given a task to consume an open rest based API from Open Weather using Ractive.js and HTML5’s Fetch 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 div#container.

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 script’s type attribute to ‘text/ractive’ - though it can be just about anything except ‘text/javascript’. We can load a template in many ways. For convenience, we’ll include it in a script tag so that we don’t need to mess around with AJAX or multiline strings.

The curly braces e.g. are holding the data set inside the ractive function with e.g. ractive.set('location', JSON.stringify( + ', ' + JSON.stringify(;

Set the ractive context

The 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

Catching events

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 fetch(request) .

Use localStorage to maintain recent search history

The city input is stored in the localStorage instance as an array and displayed as the li of ul on click of each is the weather fetching request recap-ed.

See the whole code here.