Using the PHP Last.fm API

Share this article

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

Frequently Asked Questions (FAQs) about Using the Last.fm API

How do I get started with the Last.fm API?

To get started with the Last.fm API, you first need to create an account on Last.fm. Once you have an account, you can apply for an API key. This key is unique to you and will be used to authenticate your requests to the API. After obtaining the key, you can start making requests to the API. The Last.fm API documentation provides detailed information on how to make these requests and what kind of data you can expect in return.

What kind of data can I access with the Last.fm API?

The Last.fm API provides access to a wide range of data related to music. This includes information about artists, albums, tracks, and user data. For example, you can retrieve data about an artist’s top tracks, similar artists, and upcoming events. You can also access album information like track listings and album art. User data includes listening habits and playlists.

How do I handle errors when using the Last.fm API?

When using the Last.fm API, errors can occur for various reasons such as invalid parameters, server issues, or exceeding the rate limit. These errors are returned in the response from the API. It’s important to handle these errors in your code to ensure your application continues to function correctly. You can do this by checking the status code in the response and taking appropriate action based on the error.

Is there a limit to the number of requests I can make to the Last.fm API?

Yes, there is a limit to the number of requests you can make to the Last.fm API. This is known as rate limiting. The exact number of requests you can make per day depends on the type of account you have. If you exceed this limit, you will receive an error message in response to your requests.

Can I use the Last.fm API for commercial purposes?

The Last.fm API is primarily intended for non-commercial use. If you wish to use the API for commercial purposes, you should contact Last.fm directly to discuss the possibility of a commercial license.

How do I authenticate with the Last.fm API?

To authenticate with the Last.fm API, you need to use your unique API key. This key is included in every request you make to the API. The key is used to identify you and ensure that you have permission to access the data.

Can I access user data with the Last.fm API?

Yes, you can access user data with the Last.fm API. This includes data about a user’s listening habits, playlists, and loved tracks. However, you must have the user’s permission to access this data.

How do I search for data with the Last.fm API?

The Last.fm API provides several methods for searching for data. You can search for artists, albums, tracks, and users. The search methods return a list of results that match your search query.

What programming languages can I use with the Last.fm API?

The Last.fm API is a RESTful API, which means it can be used with any programming language that can make HTTP requests and parse JSON or XML data. This includes languages like Python, JavaScript, Ruby, and many others.

How do I test my requests to the Last.fm API?

You can test your requests to the Last.fm API using a tool like Postman. Postman allows you to make requests to the API and view the response in a user-friendly format. This can be very helpful for debugging and ensuring your requests are formatted correctly.

Daniel GafitescuDaniel Gafitescu
View Author

Daniel Gafitescu is a senior PHP developer working for Pentalog in Iasi, Romania. He loves new web development technologies, and enjoys watching movies and games from English Premiership, playing soccer with friends, and most of all spending time with his newborn son and his lovely wife.

Intermediate
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week