Keith’s Blog Random thoughts on a variety of subjects

23Dec/080

Writing a last.fm plug-in for Wordpress – Part One: The last.fm API

last.fm is an online music listening and recommendation service that began life as a University project by one of it's cofounders,  Richard Jones. In addition to generating custom online "radio stations", users can create a profile that keeps track of the music they listen to. This process is called scrobbling and is used as a baseline for generating recommendations and custom playlists. To keep the data flowing, last.fm provides an easy-to-use API based on passing XML over HTTP.

This post is the first in a series of three exploring this API, and showing how the API can used to create a Wordpress plug-in for displaying information from your last.fm profile on your blog. In this first post, we'll take a look at the last.fm API, and create some simple PHP scripts to test out the API. In the second post, we'll turn our simple scripts into a complete PHP application. In the third post, we'll create a Wordpress plug-in that leverages our PHP application to display our last.fm data on a blog.

The last.fm API is accessed in two ways. For querying data, a simple HTTP GET is used, passing any variables as part of the request URL. This method does not require authentication, and returns data as an XML document in response to GET. All of the examples in this series of posts use this method. For API methods that modify a user's data, HTTP POSTs are used along with an authentication callback to the originating web site. Each type method requires a freely available API key. The examples here use my API key - I recommend that you sign up for your own, although all of the examples here will work with any recognized API key.

For our Wordpress plug-in, we are going to display the last.fm user's Album Chart. This is a personalized Weekly Top Album list for each user, showing the albums that received the greatest number of plays during the previous week. The URL to call to get the Album Chart looks like this:

http://ws.audioscrobbler.com/2.0/?method=user.getweeklyalbumchart&
user=keithlawless&api_key=14d5668dc30efbc02489d78dfc32da26

This URL is very similar to the rest of the query API's: a method name is passed which takes the form object.action, followed by a user name (if needed) and the caller's API key. The call returns an XML document. You should be able to be paste the URL above into your browser and see the most recent Album Chart for my last.fm account.


    
        
            The Tangent
            Not As Good As The Book
            
10
            http://www.last.fm/music/The+Tangent/Not+As+Good+As+The+Book
        
        
            Porcupine Tree
            The Sky Moves Sideways
            61b42968-ed19-45cd-a56e-43f5f3fa0d71
7
            http://www.last.fm/music/Porcupine+Tree/The+Sky+Moves+Sideways
        
        
            Porcupine Tree
            Fear of a Blank Planet
            
6
            http://www.last.fm/music/Porcupine+Tree/Fear+of+a+Blank+Planet
        
        
            Robert Fripp
            Radiophonics Soundscapes vol.1: Live in Argentina
            
6
            http://www.last.fm/music/Robert+Fripp/Radiophonics+Soundscapes+vol.1%3A+Live+in+Argentina
        
        
            Carole King
            Carole King - Her Greatest Hits: Songs Of Long Ago
            
2
            http://www.last.fm/music/Carole+King/Carole+King+-+Her+Greatest+Hits%3A+Songs+Of+Long+Ago
        
    

Each returned XML document will contain a status attribute in the lfm element. If the call was successful, there will be one child element containing the result - in this case a weeklyalbumchart element. This element contains a series of album elements - one for each album on our Chart.

Accessing the last.fm API from a PHP script is easy because of two nice features of PHP. First, PHP will accept a URL in most places where a local file name is called for. This allows you to quickly get the result of an HTTP call as if the result was a file on your hard drive. Second, PHP contains a simple XML parsing library called SimpleXML that allows XML documents to be treated like native PHP objects. The following PHP script calls the same URL as above, and creates an HTML list of albums from the Album Chart.

 <html>
 <body>
    <?php
        $apikey = "14d5668dc30efbc02489d78dfc32da26";
        $user = "keithlawless";
        $url = "http://ws.audioscrobbler.com/2.0/?method=user.getweeklyalbumchart&user=" .
            $user . "&api_key=" . $apikey;

        $input = file_get_contents($url)
            or die('Could not access file: $url');

        $xmlobj = simplexml_load_string($input); 

        $return_code_array = $xmlobj->xpath("@status");

        print "<h2>Status code was: " . $return_code_array[0] . "</h2>";

        print "<ul>";
        foreach( $xmlobj->weeklyalbumchart->album as $album ) {
            print "<li><a href=\"" . $album->url . "\">" .
                $album->artist . " - " . $album->name . "</a>";
        }
        print "</ul>";
    ?>
</body>
</html>

In line 6 of this example, we assemble the URL to pass to last.fm. In line 9, we use the php function file_get_contents to call the URL and return the resulting XML document as a string. A call is made to simplexml_load_string() on line 12 - this converts the XML document to a PHP object. The simplexml class allows xpath expressions - this is demonstrated on line 14, where we use the xpath expression "@status" to return all status attributes in the XML document as an array. On line 16 we displayed the first (and only) occurrence of status. Lines 19-22 is a loop over all of the album elements that are children of the weeklyalbumchart element. Each of the album elements is a SimpleXML object as well - allowing the url, artist, and name elements to be accessed using the normal "arrow" notation.

The resulting page is shown here:
dec23screen1

For the plug-in, it would be nice to display more information about each album in the Album Chart. To do that, we'll use the album.getInfo API method. A sample URL for this method is:

http://ws.audioscrobbler.com/2.0/?method=album.getinfo&
artist=Porcupine%20Tree&album=The%20Sky%20Moves%20Sideways&
api_key=14d5668dc30efbc02489d78dfc32da26

Note that this URL does not require a username field in the request since the album information isn't specific to a user. However, a valid API key is required. The resulting XML document looks something like this (some elements are removed to save space).




    The Sky Moves Sideways
    Porcupine Tree
    1429130
    61b42968-ed19-45cd-a56e-43f5f3fa0d71
    http://www.last.fm/music/Porcupine+Tree/The+Sky+Moves+Sideways
        5 Sep 1995, 00:00
    http://userserve-ak.last.fm/serve/34s/12007055.jpg
    http://userserve-ak.last.fm/serve/64s/12007055.jpg
    http://userserve-ak.last.fm/serve/174s/12007055.jpg
    http://userserve-ak.last.fm/serve/300x300/12007055.jpg
26561
250718


Of particular interest in this XML are the image tags. In the next post when we create a complete PHP application, we'll use this information to put a little image next to each entry on our chart. At this point, you should note that not all of the album elements will be present for every album. last.fm will record each album and track that you listen to based on the tagging information contained in the track. However, not all artists are in last.fm's internal databases.

That's it for this post - keep an eye out for Part 2 where we'll put all of this together into a complete PHP application.