Using the PHP Last.fm API

If you’re like me and listen to music while coding, and you like keeping a record of the songs you’ve listened to, then you’ve probably heard of Last.fm.

Last.fm is a social website which has a music recommendation engine at its core. It keeps track of its users’ music tastes, and offers events, wikis, and discographies for artists. All of the data is gathered using a Audioscrobbler database plugin installed with each user’ music player (Spotify, Winamp, iTunes, etc.). Above all, Last.fm has an rich and impressive API which developers can use to build mobile and web mashups.

If you are building a site for a band or artist and you want to make it more social using Last.fm, it’s a must to use their API. In this way artists and fans can become connected and fans can stay up to date on concerts and new albums.

In this article I show you how to query the Last FM API to get information to build a fan website for Coldplay. We start with getting the basics about the band, then get their most popular song, the contents of their albums, and a list of the events where the band is going to play for fans to get tickets.

Getting Started

In order to get an API account, you need to have a Last.fm user account first. Login with your user account and then go to www.last.fm/api/account to get an API account. When you apply for an API account you have 4 options: Commercial Use, Commercial-Promotional Use, Bespoke Use, and Non-commercial Use. Specify your application’s name, a description, and website, and you’ll be given an API key and secret.

As with all major API services, there are a bunch of different libraries available for different programming languages, including PHP. I’ll be using the PHP Last.fm API library created by Felix Bruns and hosted on GitHub. Clone the project or download the ZIP file and extract it into your working directory.

Issuing Requests

The Last.fm API is REST-based and uses XML-formatted responses, but this detail is abstracted from us by the PHP Last.fm API library. We can interface with Last.fm through the methods.

The Last.fm artist resource returns information about an artist, events the artist is performing, and the artist’s most popular tracks. To start, let’s search for an artist using the library’s Artist::search() method.

<?php
require __DIR__ . "/src/lastfm.api.php";
require __DIR__ . "/config.php";

// set api key
CallerFactory::getDefaultCaller()->setApiKey(LAST_FM_API_KEY);

// search for the Coldplay band
$artistName = "Coldplay";
$limit = 1;
$results = Artist::search($artistName, $limit);

echo "<ul>";
while ($artist = $results->current()) {
    echo "<li><div>";
    echo "Artist URL: " . $artist->getUrl() . "<br>";
    echo '<img src="' . $artist->getImage(4) . '">';
    echo "</div></li>";

    $artist = $results->next();
}
echo "</ul>";

Artist::getEvents() returns a listing of events the artist is playing.

<?php
// search for the Coldplay band events
$artistName= "ColdPlay";
$events = Artist::getEvents($artistName);
if (!empty($events)) {
    echo "<ul>";
    foreach ($events as $key => $evt) {
        echo "<li><div>";
        echo "Event Number: " . ($key + 1) . "<br>";
        echo "Event Name: " . $evt->getTitle() . "<br>";
        echo "Artists: " . implode(", ", $evt->getArtists()) . "<br>";
        echo "Venue: " . $evt->getVenue()->getName() . "<br>";
        echo "Location: " . 
            $evt->getVenue()->getLocation()->getStreet() . " " .
            $evt->getVenue()->getLocation()->getCity() . " " .
            $evt->getVenue()->getLocation()->getCountry() . "<br>";
        echo "Description: " . $evt->getDescription() . "<br>";
        echo "Event URL: " . $evt->getUrl() . "<br>";
        echo "</div></li>";
    }
    echo "</ul>";
}

Artist::getTopTracks() gets the post popular tracks by an artist.

<?php
// get top tracks for Coldplay
$artistName= "Coldplay";
$tracks = Artist::getTopTracks($artist_name);
echo "<ul>";
foreach($tracks as $key => $track) {
    echo "<li><div>";
    echo "Track Number: " . ($key + 1) . "<br>";
    echo "Title: " . $track->getName() . "<br>";
    echo "Played: " . $track->getPlayCount() . " time(s)<br>";
    echo "Duration: " . $track->getDuration() . " seconds<br>";
    echo "Track URL: " . $track->getUrl() . "<br>";
    echo "</div></li>";
}
echo "</ul>";

The album resource returns information about artists’ albums. Album::getInfo() retrieves the full track-listing for an album.

<?php
// get top tracks for Coldplay
$artistName= "Coldplay";
$albumName = "Mylo Xyloto";
$album = Album::getInfo($artistName, $albumName);
echo "<div>";
echo "Number of Plays: " . $album->getPlayCount() . " time(s)<br>";
echo 'Cover: <img src="' . $album->getImage(4) . '"><br>";
echo "Album URL: " . $album->getUrl() . "<br>";
echo "</div>";

Authenticating Your Mashup

Music is a big part of social interaction; I like to see what my friends are listening to so I can potentially discover artists I’ve never heard before and become a fan. We can get user information from the API and use it in our own mashup.

It’s a bit odd that Last.fm doesn’t use OAuth as other major social sites do. Instead they use a similar approach but having a single token instead of a access token, and access token secret as the Oauth uses. A description of the flow can be found at www.last.fm/api/webauth. But again, this is mostly an implementation detail that’s been abstracted away by our library.

The first step is to request permission to retrieve information about a user. Once the mashup is authenticated, Last.fm returns to a callback URL after which we can retrieve the desired information.

<?php
require __DIR__ . "/src/lastfm.api.php";
require __DIR__ . "/config.php";

CallerFactory::getDefaultCaller()->setApiKey(LAST_FM_API_KEY);

// create the callback url
$callback = "http://" . $_SERVER["HTTP_HOST"] . "/callback.php";
$url = "http://www.last.fm/api/auth/?api_key=" . LAST_FM_API_KEY . "&cb=" . $callback;
echo '<a href="' . $url . '">Authenticate with Last.fm</a>';

A user will click on the link and be taken to the Last.fm authentication page. After the user is authenticated, she will be redirected back to site and we’ll have the token necessary to issue requests.

<?php
// get last top 10 track listen by user "gafitescu"
$user = "gafitescu";
$tracks = User::getRecentTracks($user, 10);
echo "<ul>";
foreach($tracks as $key => $track) {
    echo "<li><div>";
    echo "Track Number: " . ($key + 1) . "<br>";
    echo "Title: " . $track->getName() . "<br>";
    echo "Artist: " . $track->getArtist() . "<br>";
    echo "Album: " . $track->getAlbum() . "<br>";
    echo "Track URL: " . $track->getUrl() . "<br>";
    echo "</div></li>";
}
echo "</ul>";

// get user's friends
$friends = User::getFriends($user);
echo "<ul>";
foreach ($friends as $friend) {
    echo "<li><div>";
    echo "Friend: " . $friend->getName() . "<br>";
    echo "Country: " . $friend->getCountry() . "<br>";
    echo "Age: " . $friend->getAge() . "<br>";
    echo "</div></li>";
}
echo "</ul>";

Conclusion

In a world that everything tends to be more and more connected, and now that Open Graph is becoming standard, connecting fans with their favorite artists its very important, and Last FM does it very well through its API. Being open allow you to enhance your community and raise awareness of your product/idea and the best way to do that it’s by having a public API.

Image via Fotolia

Win an Annual Membership to Learnable,

SitePoint's Learning Platform

  • zlajonja

    It is beyond me how nobody ever commented on this brilliant post. :) kudos.

    Just one quick question.. I cannot seem to find config.php anywhere… Been searching through and though the github and being over here reading through letter by letter.. I am sure ‘I be blind…’ and the solution is pretty simplistic in nature…

  • DarkJavier

    Hi! I’m new in API. This morning I woke up thinking about a last.fm program idea, and I think I would be able to develop a program, but I know nothing about how to run it.
    My informatics are basic, I just know how to work in MatLab and Octave.
    How can I paste my code into somewhere to have access for it?
    Thank you very much!
    Javi

    • http://www.gafitescu.ro Daniel Gafitescu

      Hi “DarkJavier”
      Well you need to run PHP and call the scripts in browser.
      If you have Windows just install WAMP and place the code in the www dir and if you are on a Mac Os X use MAMP.
      It’s server side programing and it’s quite different than Mathlab or Octave.

  • JN

    I can make my own player to play last.fm songs? Let’s say I make my own button and on click to start to play without to go from my page or to put a logo from last.fm