6. Display images from a web service

We have some great charts and tables to visualize our data, but what about actual images? We can use standard web technologies with the Splunk Web Framework, so let's get data from an external web service and visualize it directly in our Splunk app.

One of our charts shows us the top artists that users search for, so let's show images of the artists. As it turns out, there's a web service called Last.fm that takes the names of artists and returns images of them. First, you'll need to get your own developer API key to make requests to this service (the web site has directions for you to follow). With the developer API key, we can tie our Splunk data to the Last.fm API, using standard REST calls from the browser client.

While we're at it, let's consider how to display the transitions between images—this Flux Slider widget looks nice, let's try this in our app too.

    Note  At this time, Google Chrome is the only browser that supports the Flux Slider.

After following the Last.fm API documentation, and with some prior knowledge of jQuery.get, we can add some JavaScript code to tie it all together. And notice how very little of this code is Splunk related―almost all of the code could be used in any web app to get data from a third-party web service.

  1. Find this line of code again:
  2.         data.on("data", formatResults);

    Add this JavaScript below that line—and make sure to put in your own developer API key:

            //
            // LASTFM CODE
            //
    
            // Get the search manager containing artist names
            var searchDownloadsData = search1.data("results", {
                output_mode: "json_rows",
                count: 0
            });
    
            // Wait for artist names to be available
            searchDownloadsData.on("data", function(results) {
                if (!searchDownloadsData.hasData()) {
                    return;
                }
    
                // TO DO: add your API key here
                var apiKey = "";
    
                if (!apiKey) { alert("Missing Last.fm API key. Please grab one and modify your JavaScript code to include it."); return; }
    
                // Get list of artist names
                var artists = _.map(results.collection().toJSON(), function(item) { return {name: item.search_terms}; });
    
                var normalize = function(s) {
                    return $.trim(s).toLowerCase();
                };
    
                // Begin asynchronous fetching of all artist images from Last.fm
                var countdown = artists.length;
    
                for (var i = 0; i < artists.length; i++) {
                    $.get(
                        "http://ws.audioscrobbler.com/2.0/",
                        {
                            "method": "artist.getInfo",
                            "api_key": apiKey,
                            "artist": artists[i].name,
                            "format": "json"
                        },
                        function(data) {
                            var artist = _.find(artists, function(a) { return normalize(a.name) === normalize(data.artist.name); });
    
                            artist.img = _.find(data.artist.image, function(img) { return img.size === "mega"; })["#text"];
    
                            if (--countdown === 0) {
                                // All artist images have been fetched, render the UI
    
                                // TO DO: UI CODE
    
                            }
                        }
                    );
                }
            });

    If we were to open the debugger, we'd see that eventually we end up with an artists array containing artist names and image URLs.

  3. Now to display the images using the Flux Slider. We'll need to make some changes to the layout by adding a new container (<div id="slider"></div>) for the Flux Slider to bind to.
  4. Find this code:

        </div>
        <!-- End first row -->

    Just above those lines, insert the following code:

            <div id="slider-panel" class="dashboard-cell">
                <div class="dashboard-panel">
                    <!-- Flux Slider widget -->
                    <div class="dashboard-element">
                        <div id="slider"></div>
                    </div>
                </div>
            </div>
  5. Let's require the library for the Flux Slider. Find the following code:
  6.     paths: {
            'jquery-ui': 'http://code.jquery.com/ui/1.10.0/jquery-ui',
            'd3': 'http://d3js.org/d3.v2.min',
            'sankey': 'http://bost.ocks.org/mike/sankey/sankey',
            'sankey-helper': '{{SPLUNKWEB_URL_PREFIX}}/static/app/musicdashboardtutorial/sankey-helper'
        },
        shim: {
            'jquery-ui': {
                deps: ['jquery']
            },
            'sankey': {
                deps: ['d3']
            },
            'sankey-helper': {
                deps: ['sankey']
            }
        }

    Replace it with this code:

        paths: {
            'jquery-ui': 'http://code.jquery.com/ui/1.10.0/jquery-ui',
            'd3': 'http://d3js.org/d3.v2.min',
            'sankey': 'http://bost.ocks.org/mike/sankey/sankey',
            'sankey-helper': '{{SPLUNKWEB_URL_PREFIX}}/static/app/musicdashboardtutorial/sankey-helper',
            'flux': 'http://www.joelambert.co.uk/flux/js/flux'
        },
        shim: {
            'jquery-ui': {
                deps: ['jquery']
            },
            'sankey': {
                deps: ['d3']
            },
            'sankey-helper': {
                deps: ['sankey']
            },
            'flux': {
                deps: ['jquery']
            }
        }
  7. Finally, let's add the code to display the Last.fm images in the Flux Slider. Find this line of code:
  8.                             // TO DO: UI CODE

    Replace it with the following code:

                                // FLUX SLIDER UI CODE
                                var $slideShow = $('#slider');
    
                                $slideShow.empty();
    
                                _.each(artists, function(artist) {
                                    var $el = $('<img src="' + artist.img + '" title="' + artist.name + '" class="artist-image" />');
                                    $slideShow.append($el);
                                });
    
                                $slideShow.show();
    
                                new flux.slider('#slider', {
                                    pagination: false,
                                    captions: true,
                                    height: $('#slider-panel .dashboard-panel').height(),
                                    width: $('#slider-panel .dashboard-panel').width()
                                });
  9. Now, save changes, refresh and reload if needed, then navigate to your dashboard (remember to view it in the Google Chrome browser). You should start seeing the artist images after a moment.
  10. Last.fm images in Flux Slider

For your reference, here's the final version of the music_html.html page.

Now we've shown you an example of how to use available web technologies with components from the Splunk Web Framework to create a visually interesting and dynamic Splunk app. Hopefully this inspires you to create your own!