Create a Bitcoin Price Index Watcher in HTML5

Everyone is talking about Bitcoin. The Bitcoin madness and the Blockchain revolution seem to be taking over the world. So, why not learn how to consume REST Web Services in HTML5 by creating a Bitcoin Price Index Watcher?

In that tutorial, you will learn how to make AJAX requests in HTML5 by consuming a Web Service provided by CoinDesk and how to parse the JSON data from this service to display it in the HTML page. We will use this Web Service:

Note that you can discover this tutorial in this video on YouTube:

You can discover the response returned by a call on the Bitcoin Price Index Watcher API :

Response for a Call on the BPI API

As you can see, we could get the Bitcoin Price Index in US Dollars, GB Pounds, and Euros. Besides, we will display also the last updated time for the values.

Creating the HTML page

First, we start by creating the HTML page. It will be pretty simple with one logo and a simple div centered which will be used to display the data obtained from the Web Service.

Consuming the BPI API

Now, it’s time to write the Javascript code to consume the Bitcoin Price Index API from CoinDesk. For that, we are going to use directly AJAX with the XMLHttpRequest. We define a callback function on the onreadystatechange property of this object. In that function, we check the ready state and a 200 HTTP Status Code before trying to read the response from the API call.

The response is in JSON format. To parse it, we use the parse method of the JSON object which is available in standard in Javascript. Finally, we will write a parseJson function to read the data returned by the JSON.parse call. To execute the AJAX request and consuming the BPI API, we call the open method of the XMLHttpRequest instance and then, we call its send method.

Reading the JSON data

The final step is to write a parseJson method to read the data parsed and returned by the JSON.parse call. The data are stored in an array. So, it is simple to read the data and then to build HTML to display the values on the div:

Complete Source Code

Finally, it gives us the following code for our Bitcoin Price Index Watcher in HTML5:

Bitcoin Price Index Watcher in Action

To test our Bitcoin Price Index Watcher in live, you can go just here on the SSaurel’s Blog:

This is a screenshot of the final result :

Bitcoin Price Index Watcher in Action

Don’t hesitate to give it a try and share your thoughts concerning this tutorial in comments.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *