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 learning how to consume REST Web Services in HTML5 by creating a Bitcoin Price Index Watcher?
In that tutorial, you are going to learn how to make AJAX requests in HTML5 by consuming a Web Service provided by CoinDesk and finally how to parse the JSON data got from this service to display it on the HTML page. We will use this Web Service:
https://api.coindesk.com/v1/bpi/currentprice.json
Note that you can discover this tutorial in video on YouTube:
You can discover the response returned by a call on the Bitcoin Price Index Watcher API:
Like 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 got 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: https://www.ssaurel.com/cryptocoins/bpi.html
This is a screenshot of the final result:
Don’t hesitate to give it a try and share your thoughts concerning this tutorial in the comments.
This tutorial was first published on the Medium space of Sylvain Saurel.
Leave a Reply
You must be logged in to post a comment.