Last.fm API: example project

Using the Last.fm API and JavaScript libraries to get access to data from your Last.fm profile.

Introduction

The Last.fm API offers great functionality such as the recommender system, Last.fm scrobbling and accessing and modifying your Last.fm profile information, aside from providing a large amount of data. To use the API, libraries have been developed for several technologies, such as JavaScript, PHP, Python and Actionscript among others (Last.fm, 2012).

In this document we will be looking at the JavaScript library. One of the advantages of JavaScript is that it can be used in the browser – i.e. client side (Netscape Communications Corporation, 1999). This usually avoids the need of a server to write small applications.

First we’ll be looking at what we’ll need to get started. Then we’ll create a small application that requires no authentication. The next step will be to call methods of the API that do require authentication. The explanations provided for this second tutorial will be a bit more concise, as you should be a bit familiar with the API by then. We’ll conclude with some final thoughts.

Getting started

Last.fm API account

To build an application using the Last.fm API, you have to create an API account first. Once you have been registered, you’ll receive an API key and an API secret.

For testing purposes it will also be handy to have a Last.fm account of your own. So if you haven’t got one already sign up at their website. You might also want to download their Scrobbler desktop application. This will collect data from your music players to generate profile information that will be used to generate recommendations.

Last.fm API JavaScript Library

There are already several interesting applications that make use of the Last.fm API. Even more interesting perhaps is that some developers distribute free JavaScript libraries that act like a façade on the Last.fm API. The library we’ll be using here can be found on github and is written by Felix Bruns. Note that the same developer has a library for PHP as well.

Fork or download the JavaScript files and save them to your computer. The next paragraph describes how to include these files into your project.

Example project

Top artists

Project setup

Start by creating a new, folder for example “lastfm-topartists” and add a new blank file with html extension, e.g. topartists.html, as we’ll be getting the top artists for a certain user. The next thing we’ll need to do is to add the JavaScript libraries to the topartists.html file. To keep things organized it is recommended to create a sub-folder in the lastfm-topartists folder – for example “js”, and add the JavaScript files of the library to this folder. Adding the scripts to your HTML file can be done adding the code in Listing 1 to the HTML head element.

adding js files to html

Listing 1: adding JavaScript files to an HTML file

Once you’ve done this we should create a new .js file, say topasrtists.js and add it to the HTML file in a similar fashion – alternatively you could start coding directly in the HTML file between script tags, but it is usually preferred to work with separate JavaScript files.

Getting the data

Open the new JavaScript file topasrtists.js and add the source code to it as shown in Listing 2. The first line creates a new LastFMCasche object, the next statement creates a new LastFM object. Make sure you’ll replace the placeholders <your_api_key> and <your_api_secret> with your own API key and API secret.

Listing 2 : JavaScript implementation to instantiate a LastFMCasche and LastFM object.

var cache = new LastFMCache();

var lastfm = new LastFM({
    apiKey    : 'your_api_key',
    apiSecret : 'your_api_secret',
    cache     : cache
});

The next thing we’ll need to do is to get the top artists from the server for a given user. The code that implements this functionality is shown in Listing 3.

Listing 3 : getting top artists from Last.fm for a user

window.document.onload = lastfm.user.getTopArtists({
    user: '',
    limit: 10
},
{
    success: function(data) {
        // do something
    },
    error: function(data) {
        alert(data.error + " " + data.message);
    }
});

Showing the data

To show the data on the web page, we’ll need to create an HTML String and append it the HTML document object model (DOM). Add a new div element to your HTML page and give it an id, for example top-artists; this is shown in Listing 4. The following step is to create an ol element (ordered list) in the function after success – where it says “do something”, and iterate through the top artsists, adding them to the list one by one, as shown in Listing 5. What this code does is to get the name for each artist in the topartists list of the data object and insert it between li tags. The resulting String is set as the innerHTML value of the element with the topartists id.

Listing 4: the #topartists div

<div id="topartists"></div>

Listing 5 : the implementation of the data visualization

var list = '<ol>';
for (var i = 0; i < data.topartists.artist.length; i++) {
    list += '<li>' + data.topartists.artist[i].name + '</li>';
}
document.getElementById('topartists').innerHTML = list + '</ol>';

Finishing up

Open your HTML page with a browser, e.g. Google Chrome to see if everything worked.

Recommended artists

For the next application we won’t be looking into detail what the visualization does. Instead we will see what we need to call a method that requires authentication. This process consists out of three steps:

  1. Get a token;
  2. Get a session object;
  3. Call the authenticated method.

Getting a token

The user has to allow your application to access and possibly change his/her profile. In order to do this we’ll redirect the user to http://www.last.fm/api/auth/ and if the he/she grants us access, we’ll receive a token. Listing 6 shows how to implement this. Note that this implementation also uses an optional callback parameter; this will redirect the user after granting access to an URL of your choice.

To retrieve the token from the URL, it is an option to make use of the JavaScript libraries jQuery and jQuery-URL-Parser.

Listing 6 : redirecting to get a token

var api_key = 'your_api_key';
var cb = 'your_callback_url';
window.location = 'http://www.last.fm/api/auth/?api_key=' + api_key + '&cb=' + cb;
var token = $.url().param('token');

Getting a session object

To get the session object we’ll have to call the method getSession on the auth field of our LastFM object, as can be seen in Listing 7.

Listing 7 : calling the getSession method

lastfm.auth.getSession({
    token: token
},
{
    success: function(data_sess) {
        // do something
    },
    error: function(data_sess_error) {
    	// error msg
    }
});

Calling the authenticated method

Finally we’ll have to call the authenticated method. In this case we’ve chosen for the method getRecommendedArtists on the user field of the LastFM object. How this can be done is shown in Listing 8; note that this code has to be pasted in the success function of getSession.

Listing 8 : calling the getRecommendedArtists method

lastfm.user.getRecommendedArtists({
    user: user,
    limit: 10
},
    data_sess.session,
{
    success: function(data_recs) {
         // do something
    },
    error: function(data_recs_error) {
    	// error msg
    }
});

Final thoughts

Using the Last.fm API can be used to create lightweight JavaScript applications. Although the documentation could be better, it is still relatively easy to get some quick results.

The full example project can be found on github.

References

Last.fm, 2012. API – Last.fm. [Online] Available at: http://www.last.fm/api/ [Geopend 15 December 2012].

Netscape Communications Corporation, 1999. Client-Side JavaScript Guide. [Online] Available at: http://docs.oracle.com/cd/E19957-01/816-6409-10/intro.htm#1009369 [Geopend 15 December 2012].

Advertisements

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