Flask, JSON and the Google Charts API


This tutorial will teach you how to build a Flask app that combined with JSON and the Google Charts API. If you have no experience with Flask before I recommend reading my previous tutorials, they are great fun!

Download Flask Examples

Installing Flask

Install Flask using the command below:

$ pip install Flask

Create a file called hello.py

from flask import Flask
app = Flask(__name__)
 
@app.route("/")
def hello():
    return "Hello World!"
 
if __name__ == "__main__":
    app.run()

Finally run the web app using this command:

$ python hello.py
* Running on http://localhost:5000/

Open http://localhost:5000/ in your webbrowser, and “Hello World!” should appear.

Get JSON data

To display awesome charts we first need some data. There are two common ways to get data in web apps: data from servers using an API (usually JSON) and data from databases. I use the Fixer.io JSON API to get some financial data, but any JSON API should do. If you are unfamiliar with JSON, see this article.

We wrote this script to get the exchange rates:

import json
import urllib2
 
def getExchangeRates():
    rates = []
    response = urllib2.urlopen('http://api.fixer.io/latest')
    data = response.read()
    rdata = json.loads(data, parse_float=float)
 
    rates.append( rdata['rates']['USD'] )
    rates.append( rdata['rates']['GBP'] )
    rates.append( rdata['rates']['JPY'] )
    rates.append( rdata['rates']['AUD'] )
    return rates
 
rates = getExchangeRates()
print rates

Google Charts API with Flask

With the Google Charts API you can display live data on your site. There are a lot of great charts there that are easy to add to your Flask app. We simply give the data that we got from the server through JSON and parsed, to the Google Charts API.

Create a flask app with the directory /templates/ for your templates. This is the main Flask code:

from flask import Flask, flash, redirect, render_template, request, session, abort
import os
import json
import urllib2
 
tmpl_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')
app = Flask(__name__, template_folder=tmpl_dir)
 
def getExchangeRates():
    rates = []
    response = urllib2.urlopen('http://api.fixer.io/latest')
    data = response.read()
    rdata = json.loads(data, parse_float=float)
 
    rates.append( rdata['rates']['USD'] )
    rates.append( rdata['rates']['GBP'] )
    rates.append( rdata['rates']['HKD'] )
    rates.append( rdata['rates']['AUD'] )
    return rates
 
@app.route("/")
def index():
    rates = getExchangeRates()
    return render_template('test.html',**locals())      
 
@app.route("/hello")
def hello():
    return "Hello World!"
 
 
if __name__ == "__main__":
    app.run()

And we have this template:

{% block body %}
 
  <script type="text/javascript" src="https://www.google.com/jsapi"></script>
  <div id="chart_div"  style="width: 900px; height: 300px;"><div>
 
 
<script type='text/javascript'>//<![CDATA[ 
 
google.load('visualization', '1', {packages: ['corechart', 'bar']});
google.setOnLoadCallback(drawBasic);
 
function drawBasic() {
 
      var data = google.visualization.arrayToDataTable([
        ['Currency', 'Rate', { role: 'style' }],
        ['USD', {{rates[0]}}, 'gold'],
        ['GBP', {{rates[1]}}, 'silver'],
        ['HKD', {{rates[2]}}, 'brown'],
        ['AUD', {{rates[3]}}, 'blue']
      ]);
 
      var options = {
        title: 'Exchange rate overview',
        chartArea: {width: '50%'},
        hAxis: {
          title: '',
          minValue: 0
        },
        vAxis: {
          title: ''
        }
      };
 
      var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
 
      chart.draw(data, options);
    }
//]]>  
 
</script>
 
 
{% endblock %}

Result:

Flask App
Flask App

 


7 thoughts on “Flask, JSON and the Google Charts API

  1. Admpecam - August 5, 2016

    Thanks. The article is really helpful. I just have a quick question: In what format the data is in the link in : response = urllib2.urlopen(‘http://api.fixer.io/latest’).
    I am in the process of using google annotation chart using flask. So was really curious how to get the data, as I am storing data in mongodb? Thanks

    1. Frank - August 5, 2016

      Hi Adm, this format is json. You can load the data with json.loads(json_data) and access it as json object.

      Example of using the json object:

      import json
       
      array = '{"base":"EUR","date":"2016-08-05","rates":{"AUD":1.4567,"BGN":1.9558,"BRL":3.5501,"CAD":1.4529,"CHF":1.0852,"CNY":7.411,"CZK":27.022,"DKK":7.4373,"GBP":0.8481,"HKD":8.6521,"HRK":7.4843,"HUF":310.62,"IDR":14617.71,"ILS":4.2633,"INR":74.4919,"JPY":112.73,"KRW":1237.73,"MXN":21.0282,"MYR":4.4927,"NOK":9.4022,"NZD":1.5473,"PHP":52.3,"PLN":4.2841,"RON":4.4622,"RUB":72.7967,"SEK":9.5043,"SGD":1.4953,"THB":38.848,"TRY":3.3471,"USD":1.1156,"ZAR":15.2536}}'
      data = json.loads(array)
      print(data["base"])
      print(data["rates"]["AUD"])
      1. Admpecam - August 8, 2016

        Thank you so much!

  2. Ben - January 15, 2016

    Perfect! Thank you!

  3. Abay Bektursun - June 8, 2015

    Thank you very much! Well written article!

  4. Mark Bannan - May 22, 2015

    This is an exceptional tutorial on this!!! Simple yet full of great stuff and tied together well (this has been missing from the web). Nicely done and thanks.

    1. Frank - May 22, 2015

      Thanks!