w3resource

Get the top artists and their playcounts with last.fm API

Introduction

Using last.fm API, developers may create applications to fetch and sort from a huge collection of music. In this tutorial, we will create a simple application using last.fm API. We will fetch top artists and their playcount and will render those, ordered by playcount in an HTML page.

Obtaining an API key

Go to http://www.last.fm/api. Click on the link "Get an API account". Login to last.fm if you have an account there. Optionally you may login using your Facebook account.

Create API account link

Once logged in, it will ask to select kind of application you are going to create. For now, we select Non-Commercial. Also, provide the form with Application/Device Name, Application, description and Application homepage. Click on Create account.

At the end of the process, you will end up creating an app with an API KEY.

Demo app

Outline of our app

In this app, we will fetch top artists and their playcounts and render those within an HTML page.

Code and explanation

last.fm API offers several Methods by using which you can retrieve data. In this example, we will use 'user.getTopArtists' method. We will use 'http://ws.audioscrobbler.com/2.0/?method=user.getTopArtists&user=test&api_key=4a9f5581a9cdf20a699f540ac52a95c9&limit=10&format=json&callback=?' url for fetching data. This returns JSON data. We then use Jquery to get data from that JSON and render. Code for the app as follows:

<!doctype html>
<html>
<head>
<title>Get the top artists and their playcounts using last.fm API</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<script>
$(document).ready(function() {
    $.getJSON("http://ws.audioscrobbler.com/2.0/?method=user.getTopArtists&user=test&api_key=4a9f5581a9cdf20a699f540ac52a95c9&limit=10&format=json&callback=?", function(json) {
        var html = '';
        $.each(json.topartists.artist, function(i, item) {
            html += "<p><a href=" + item.url + " target='_blank'>" + item.name + " - " + "Play count : " +item.playcount + "</a></p>";
        });
        $('#result').append(html);
    });
});
</script>
<div id="result"></div>
</body>
</html>

Previous: Creating your first app with Flickr API
Next: Twitter REST API Tutorial



Follow us on Facebook and Twitter for latest update.