drew.d.lenhart

programming, software, technology, anything on my mind...

Getting Started with a JSON API using Slim Part 3 – Charts!

2016/02/31

I had some fun in the two earlier articles, part one, part two. I showed how quickly one can create a small JSON API. In this article, I wanted to show how to put that API into use. As I explained in the first article, I use AMCharts all the time for many different types of charts. I also use the same way of building Slim JSON API's as a datafeed!

Given that we built an API and have mock data to work with, here is the line chart we want to build:

Screen Shot 2016-02-14 at 8.23.36 PM

Please read the previous articles before attempting below.

Add Slim Route

Since we have our JSON API app all set up, lets create a new get route URL to host the page. In the root folder of the project, create a "views" folder. This will hold our html file. Also create dash.html file. We need to do a couple things in index.php:

Create a path for our templates:


$app->config(array(
    'templates.path' => './views'
    ));

Also create dashboard url, notice the render() method:


$app->get('/dashboard', function() use($app) {
    $app->render('dash.html');
});

If you navigate to the following url: http://localhost/dashboard, or however your configuration is, you will be redirected to the dash.html you created earlier.

Note: You don't need to build your chart along with the API, I'm only doing this for demonstration purposes, you can create this on a separate website for example.

AMCharts

AmCharts has a pretty nifty Live Chart Builder and is what I used to get the basic building blocks going. I selected Line >> Time series, Minute option.

I wasn't too concerned with building the whole chart here. I just wanted to look and feel. Play around with the options and formatting of your chart here. In the bottom right hand the builder gives an option to save the HTML. Go ahead and copy the HTML contents and put into dash.html.

If you copied your chart right out of the Live Builder, you will notice a dataProvider, along with key and values. You can remove this dummy data as we will feed our own.

Here is the full code of dash.html:


<!DOCTYPE html>
<html>
    <head>
        <title>stJsonAPIv3 - Amchart</title>
        <meta name="description" content="chart created using amCharts live editor" />

        <!-- amCharts javascript sources -->
        <script type="text/javascript" src="http://www.amcharts.com/lib/3/amcharts.js"></script>
        <script type="text/javascript" src="http://www.amcharts.com/lib/3/serial.js"></script>
        <script type="text/javascript" src="http://www.amcharts.com/lib/3/themes/dark.js"></script>
        <script src="http://www.amcharts.com/lib/3/plugins/dataloader/dataloader.min.js" type="text/javascript"></script>
        <!-- amCharts javascript code -->
        <script type="text/javascript">
            AmCharts.makeChart("chartdiv",
                {
                    "type": "serial",
                    "dataLoader": {
                        //dont forget to adjust your url to your configuration
                        "url": "http://localhost/api/get/utilization"
                    },
                    "categoryField": "c_date",
                    //"dataDateFormat": "YYYY-MM-DD HH:NN:SS",
                    "theme": "dark",
                    "autoMarginOffset": 30,
                    "categoryAxis": {
                        "parseDates": false,
                        "autoGridCount": true,
                        "minHorizontalGap": 100,
                        "equalSpacing": false,
                        "labelsEnabled": false,
                        "startOnAxis": true,
                        "showLastLabel": true,
                        "marginBottom": 40
                    },
                    "chartCursor": {
                        "enabled": true,
                        "categoryBalloonDateFormat": "JJ:NN:SS"
                    },
                    "chartScrollbar": {
                        "enabled": true
                    },
                    "trendLines": [],
                    "graphs": [
                        {
                            "bullet": "round",
                            "id": "AmGraph-1",
                            "title": "CPU",
                            "valueField": "c_cpu",
                            "balloonText": "<span style='font-size:16px;'>CPU: [[value]] %</span>"
                        },
                        {
                            "bullet": "square",
                            "id": "AmGraph-2",
                            "title": "MEMORY",
                            "valueField": "c_mem",
                            "balloonText": "<span style='font-size:16px;'>MEM: [[value]] %</span>"
                        },
                        {
                            "bullet": "round",
                            "id": "AmGraph-3",
                            "title": "DISK",
                            "valueField": "c_cdrive",
                            "balloonText": "<span style='font-size:16px;'>DISK: [[value]] %</span>"
                        }
                    ],
                    "guides": [],
                    "valueAxes": [
                        {
                            "id": "ValueAxis-1",
                            "title": "Value"
                        }
                    ],
                    "allLabels": [],
                    "balloon": {},
                    "legend": {
                        "enabled": true,
                        "useGraphSettings": true
                    },
                    "titles": [
                        {
                            "id": "Title-1",
                            "size": 15,
                            "text": "Utilization"
                        }
                    ]
                }
            );
        </script>
    </head>
    <body style="background: grey">
        <div style="margin-top: 5%; margin-left: 10%; margin-right: 10%">
        <div id="chartdiv" style="width: 100%; height: 500px; background-color: #282828" ></div>
        </div>
    </body>
</html>

A Few Things...

I'm just going to point out a few things in the AmCharts javascript code, otherwise AmCharts provides pretty good documentation.


"dataLoader": {
//dont forget to adjust your url to your configuration
"url": "http://localhost/api/get/utilization"
},

This is where we plug in the URL of the /get/utilization endpoint created in the previous articles! Please read more on "dataLoader" in this tutorial. This is key to having your API routes correct and tested in order for AmCharts to properly read the JSON data.


"graphs": [
    {
        "bullet": "round",
        "id": "AmGraph-1",
        "title": "CPU",
        "valueField": "c_cpu",
                "balloonText": "<span style='font-size:16px;'>CPU: [[value]] %</span>"
},

Within graphs is where we start assigning the values in the JSON data to the lines we want to create. So if we look back at our JSON data output with the /api/get/utilization:

Screen Shot 2016-02-03 at 7.58.53 PM

Notice the "c_cpu" key and value in the JSON. Inserting this key into the Graph valueField, will plot the values via a line to the chart!


Thats it! This was quite a fun project to write out. What started as a small JSON API using Slim/PHP turned into a demonstration for charting purposes! I have included the demo code as well as the MySQL database that can be imported via PHPMyAdmin or other means.

Github

--Drew