The Silver Lining

Lessons & Learnings from a salesforce certified technical architect.

Salesforce Analytics API Sample Code

with 6 comments

Spider ChartA picture is worth a thousand words, so goes the justification for graphic novels. I kid, I love the hell out of graphic novels but now I’ve been sidetracked and this is only the second sentence of this post.

So, the Analytics API. I’m pretty enamoured with it as it seems is Pat Patterson, and I think that it’s one of the most useful features the platform has ever made available. Presenting the right chart (or set of charts) to a manager or executive can empower them to make business decision in minutes, powerful stuff. To that end myself and a few of my fellow Tquilites have begun building an opensource library of Analytics API demos to aid you in aiding your clients/managers/execs.

Below I’ve included a few introductory steps to help you get started. To start with you’ll need the code from github.

Step 0

I’ll be stepping through the Google Charts Stacked Bar Chart example from github so you’ll be able to test this out yourself.

Step 1 – Create a report

Certain report formats map well to certain chart formats so make sure you choose the right type of report. For example, stacked bar charts map well to matrix reports, summary charts map well to pie charts.

Once you have created your report and have some interesting data, determine the report ID and keep it somewhere safe. Report IDs always start with “00O”.

Report ID

Step 2 – Create a Visualforce Page

As it says in the heading of this section, create a new VF page. Easy peasy lemon squeezy.

Step 3 – Include the chosen JS library

As with any web-based language you’ll need to include the JS library that you want to use. I’m going to use Google Charts in this example. Note I’m also using jQuery to make the AJAX callout.

 <script type=”text/javascript” src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
 <script type="text/javascript" src="https://www.google.com/jsapi"></script>

Step 4 – Call the Analytics API

The API call can be made server-side or client-side, with this example making use of a client-side call.

    /** Fetch the JSON data representing the the report **/
    var jsonData = JSON.parse($.ajax({
        beforeSend: function(xhr) {
          xhr.setRequestHeader('Authorization', 'Bearer {!$Api.Session_ID}');
        },
        /** You'll need a URL parameter key called "id" that has a Summary Report id value **/
        url: "/services/data/v29.0/analytics/reports/{!$CurrentPage.parameters.id}",
        dataType:"json",
        async: false
        }).responseText);

The results of the callout are fed into the callback function and available through the variables “ai” and “ae” (see below).

Step 5 – Parse the resulting JSON & build the required data structure

The structure of the JSON depends on the report type but is fairly simple to understand. Be sure to use console.log() to investigate what’s going on if you get stuck.

    var chartData = new google.visualization.DataTable();

    chartData.addColumn('string', 'Stage');

    $.each(jsonData.groupingsDown.groupings, function(di, de) {
      chartData.addColumn('number', de.label);
    });

    $.each(jsonData.groupingsAcross.groupings, function(ai, ae) {
      var values = [];
      values.push(ae.label);

      $.each(jsonData.groupingsDown.groupings, function(di, de) {

        values.push(jsonData.factMap[de.key+"!"+ae.key].aggregates[0].value);
      });

      chartData.addRow(values);
    });

Step 6 – Generate the chart

Finally invoke the drawing of the chart along with any options required.

    var options = {
      title: jsonData.attributes.reportName,
      vAxis: {title: jsonData.reportMetadata.groupingsAcross[0].name},
      isStacked: true
    };

    var chart = new google.visualization.ColumnChart(document.getElementById('chart'));
    chart.draw(chartData, options);

Voila! You now know the basics of building custom charts in Visualforce (or any other web language) using the Analytics API. To try this out log into your Org and then browse to:

http://[your salesforce instance]/apex/YourPage?id=[reportId]

Feel free to use this code anyway that you can imagine and we’d be over the moon if you contribute your own awesome to what we’re building. Fork us on github.

About these ads

Written by Wes

November 10, 2013 at 4:57 pm

6 Responses

Subscribe to comments with RSS.

  1. […] Salesforce Analytics API Demo Code […]

  2. Hi Wes,
    Could you pls let us know how to make use of Analytics API as we can’t find any code regarding this API in the repository except some Metadata information regarding reports.

    Sanchit

    Sanchit

    November 11, 2013 at 8:34 am

    • I updated the post last night to include more detail but forgot to post it!

      Wes

      November 11, 2013 at 4:56 pm

  3. Just shared on LinkedIn, thanks!

    Keith Bigelow

    November 11, 2013 at 4:32 pm

  4. Code below shows dynamically sizing and displaying desired column.
    Usage: http://%5Byour salesforce instance]/apex/YourPage?id=[reportId]&col_numb=# desired column number.
    Cheers,
    -Ray

    // Note: aggregates[#] is dynamically sized with var ‘size’.
    var max_col = jsonData.factMap[index.toString()+"!T"].aggregates.length – 1;
    var show_col =
    console.log(col_numb);
    if (show_col != ‘default’) {
    dataArray.push([grouping.label, jsonData.factMap[index.toString()+"!T"].aggregates[show_col].value]);
    } else {
    dataArray.push([grouping.label, jsonData.factMap[index.toString()+"!T"].aggregates[max_col].value]);
    }

    Raymond Gao

    June 2, 2014 at 5:58 pm

  5. […] Salesforce Analytics API Demo Code […]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 2,096 other followers

%d bloggers like this: