Custom Charts from the MaxCDN API
March 24, 2014 | Ivan Dabic
While playing around with the MaxCDN Python API, I stumbled across pygooglechart, a nice library for generating reports. Today we’ll cover how to combine API results with explains how to combine charts with various usage reports from the CDN.
To get started, install our API library and the charting library with python-pip:
$ sudo pip install maxcdn $ sudo pip install pygooglechart
Next, create a new Python script (such as gchart.py) to grab data from our API and render the chart. The following code sample charts the rate of cache hits vs misses:
from pygooglechart import PieChart2D from pygooglechart import PieChart3D from maxcdn import MaxCDN api = MaxCDN("alias", "key", "secret") def chart(): data = api.get('/reports/stats.json/daily') hitsum = data['data']['summary']['cache_hit'] misssum = data['data']['summary']['noncache_hit'] # Create a chart object of 550x200 pixels chart = PieChart3D(550, 200) # Add some data chart.add_data([int(hitsum), int(misssum)]) # Assign the labels to the pie data chart.set_pie_labels(['Hits: ' + hitsum, 'Misses: ' + misssum]) # Download the chart chart.download('rate.png') chart()
Here’s a quick walkthrough:
Lines 1-3 import the charting and API libraries we need
Line 5 creates the API object used to access the reports
Line 8-10 pulls statistics from our Reports API, in JSON format, and extracts relevant portions of the summary for quick access
Line 13-19 creates a new chart, populates the data, and sets the labels
Line 22 saves the chart to a local file
Line 23 executes the function to generate the chart (this function might be called repeatedly as part of a larger script)
Here’s the final result:
Pretty straightforward, right? And there’s a lot more you can do with our API (see the API Docs for a full list).
Want to get started with the MaxCDN API? Sign up here.