Add the Last.FM API to your website

Last.fm is a music website where users can listen to music and watch videos from their favorite artists. There are also a social networking features where users can recommend artists and songs, find upcoming artist events and find similar artists.

In addition to the website, Last.fm has rich web services including an API and features applications available to users found here. This article will show how easy it is to use Last.fm's API.

In this article, we will be using WebMatrix. WebMatrix is a free tool that allows you to create, customize, and publish webpages. It gives a number of different ways that you can create websites. One of the features is providing existing open sources applications such as WordPress, Joomla, DotNetNuke or Umbraco. WebMatrix can be downloaded for free at microsoft.com/Web/WebMatrix .

Create a website with WebMatrix

If you need help downloading and installing WebMatrix, it may be a good idea to read Getting Started with WebMatrix. The article provides step by step instructions on installing WebMatrix

Let's get started creating a new webpage with WebMatrix.

After WebMatrix is finished installing, open it. Click "Site from Template" on the WebMatrix welcome screen.

For this example we will use is an Empty Site template. This template is a full-featured HTML5 site. Click Empty site and hit ok.

Clicking ok will take you to your WebMatrix workspace. This contains information about your local host as well a provides resources on developing your site.

You’ll notice that WebMatrix allows you to move between different workspaces by selecting the buttons on the left hand side. At present the Site button is selected which gives you details on your web site, such as the URL of the site, and other tools that you can use such as monitoring your site requests. You can look into this workspaces as you work but for this article, we will be working with our Files workspace. To get to your Files workspace, click the "Files" tab on the lower left hand of WebMatrix.

Once in your Files workspace you can see all your files. Since we chose the Empty Site template, we do not have any files. Let's create a new file for our website. Click the new button on the menu ribbon.

Here you can see all the different types of files you can make. Choose the .cshtml file, give it a name and hit ok.

We now have an empty, HTML5 valid website waiting for us to add code. You may be wondering why we created a .cshtml file instead of a traditional .html file. A .cshtml file is a new, special file type for WebMatrix. This type of file can contain the usual contents of a webpage including HTML and JavaScript code but, what sets it apart from a regular .html file is that it can also contain code for programming webpages. .cshtml files let you embed ASP.NET code into your HTML page using the new Razor syntax (which is most commonly denoted using @ - similar to PHP's $).

Razor code can go anywhere on your webpage. Blocks of code (written between @{ }), single line statements, and even single variables can be put anywhere, just make sure you have the correct syntax! If you want a more in-depth introduction to WebMatrix, you can find numerous resources on the subject including the asp.net website.

We'll look at how to add a Last.fm RESTful request to our webpage but first, we must sign in or create a Last.fm account. If you already have a Last.fm account or, you're already signed in, you can skip the next section.

Create a Last.fm account

Before we get started using Last.fm's API, we need to create an account. Last.fm allows user's to have one account where they can use their website as well as use the API. On the Last.fm developer site there are a few steps on how to get started.

The first step is to apply for an API account. This is an easy step if you already have a Last.fm account. Click the "Apply for an API account link." On this page you will have the option to login or to sign up.

If you already have an account, click the "login" link. Here you will need to supply your Last.fm username and password.

If you don't have an account click the "create account" link. You'll just need to supply a username, email address, and password to create an account.

Now you'll need to apply for a API account. All you need to do is tell Last.fm what way you'll be using their API. You can do that here.

After you've supplied all the information, your API account information can be seen on your API account page. You will need to supply your API key in every web request so it is important to know where to find this information.

Now that you've got your API account set up, we can start looking at how to add the API to our website.

Add the Last.fm API to your website

Head to the Last.fm API website. Here you can see all of the different methods available for you to use in your web requests.

Clicking on a method will take you to the method's webpage with information about the method, it's parameters, and it's response. It's ideal to check out this information before you start writing your code. This article will look at two different methods, get hyped artists and get a user's recently played tracks. Let's look at the get hyped artists method first. Visit the method page.

This method is pretty straight forward. It has one required parameter - your API key. Your API key is a required parameter for every method call in the Last.fm API library. It also does not require authentication which means we can simply make a web request with our API key. A sample response can also be found on this page. This is helpful because we can see the structure of our XML response and anticipate how we're going to use it.

Now let's add our method call to our webpage.

The Last.fm API uses the RESTful format. This means that your webpage will make a request and you will receive a response with the information you requested. You can then do something with the requested information on your webpage. Because our response will be in XML (because we are using the RSS format), we can use the XMLTextReader class to parse our web response. To do that, we must define some directives. This must be done first thing on the page. At the very top of your .cshtml file, add:

@using System.Xml;
@using System.IO;
@using System.Text;

Like noted earlier, one of the nice things about the API method pages is that it provides the output parameters and an example of each method response. This is helpful to look at before we create our web request so we know what information we want to retrieve from our response.

Looking at the example response for your get hyped artists method, we can see that we probably want to get the artist's name, the url to their page on Last.fm, and an image. This means that we need variables for each of these. Add between @{ and } :

    string name = String.Empty;
    string urlLink = String.Empty;
    string imageURL = String.Empty;

Now we’re ready to add our web request. Firstly, we need to create our request uri. Anywhere in your .cshtml (if must be after the code we added earlier) add your method call:

string uri = "http://ws.audioscrobbler.com/2.0/?method=chart.gethypedartists&limit=24&api_key={your-api-key}";

Now we have constructed our uri. Make sure you replace {your-api-key} with your actual API key. Let’s add our web request and response. Like noted earlier, we can use the XMLTextReader to parse our response. Let’s create that object now also. Add below our recently added code:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);     
WebResponse response = request.GetResponse();
Stream strm = response.GetResponseStream();
XmlTextReader reader = new XmlTextReader(strm); 

Here we create our web request with our uri, get our web response and save it into a stream. We then create our XMLTextReader that we will use to parse through our response stream.

A helpful thing to know before we parse our response is to know what our response is. That way we can know if we are retrieving the correct information. You can make your web request simply by putting it in the address bar of any browser. Once the request is made you will receive the XML response in the browser. Let's try that now. Open a browser and paste your uri request into the address bar. You should see something similar to this:

This may look like a bunch of jumble and doesn't make sense but, if you right-click the page and select "view source" you can actually see the XML that makes up the web response.

Now let's back to adding the code that will parse our web response. Somewhere between <body> and </body>, add:

@{
     int itemDepth = 0;
    while (reader.Read()){
        if (reader.Name == "artist") {
            itemDepth = reader.Depth;
            reader.Read();
             while(reader.Depth != itemDepth) {  
                if(reader.Name == "name") {
                    name = reader.ReadString();
                } else if(reader.Name == "url") {
                    urlLink = reader.ReadString();
                } else if (reader.Name == "image") {
                    if (reader.GetAttribute("size") == "medium") {
                        imageURL = reader.ReadString(); 
                    }
                } 
                reader.Read();        
            }
           <p><a href="@urlLink">@name<br /><img src="@imageURL" /></a></p>
        }
    }
    response.Close();
} 

Our code reads through our response until it gets to the artist element. We then get the artist's name, url to the Last.fm page, and image url (if the attribute size is medium - we could change this to small or large). Once we’ve retrieved this information for each artist, we then print it out to our webpage. We continue to do this until we reach the end of our response.

Run your page by clicking "run" on the menu ribbon. This will open your page in your default browser. You page should look something like this:

Not very exciting is it? Let's jazz it up by adding some CSS to it. Add 2 <div>s around your Razor code (@{ }) in the body of your page:

        <div id="container">
            <div id="gallery">

Now, in the <head> of your page, add a link to an external stylesheet. Like so:

<link rel="stylesheet" type="text/css" href="StyleSheet.css" />

Now we need to create the CSS file that our webpage is linked to. Click the "new" button on the menu ribbon. Choose the file type of CSS and give it a name. Make sure that this name is the same name that your reference in your webpage.

Add the following code to your CSS file:

#container {
    width:600px; 
    margin-left: 25%; 
    border: 1px solid black; 
    padding:5px;
    height: 1000px;
}

#gallery a {
    padding:5px;
    display: block;
    float: left;
    margin: 10px;
    width: 115px;
    height: 125px;
}

#gallery img {
    display:block;
}

#gallery {
    width: 600px;
    padding-top: 0px;
    padding-right: 10px;
    padding-left: 10px;
    margin-left: 15px
}

Now run your webpage again. You should see your CSS applied to it.

It was that simple using the Last.fm API. Let's look at another method example. Check out the get user's recent tracks method page.

This method is very similar to the get hyped artists method we used earlier. One difference is that we must supply the user name for which we want to get recently played tracks. For this example you can use your own Last.fm username for that parameter.

Create a new .cshtml file. Add the following code to the top of the file:

@using System.Xml;
@using System.IO;
@using System.Text;
@{  
    string artist = String.Empty;
    string urlLink = String.Empty;
    string name = String.Empty;
    string uri = "http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user={your-username}&api_key={your-api-keyy}";
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);     
    WebResponse response = request.GetResponse();
    Stream strm = response.GetResponseStream();
    XmlTextReader reader = new XmlTextReader(strm); 
} 

Make sure you replace {your-username} with your username and {your-api-key} with your API key. This code is eerily similar to our previous code. The only thing different are our variables and our uri request string. When using other Last.fm API methods, you can use this code as a basic structure to get you started.

Now we need to add the code that parses through out XML response. Add between <body> and </body>:

@{
    int itemDepth = 0;
    while (reader.Read()){
        if (reader.Name == "track") {
            itemDepth = reader.Depth;
            reader.Read();
            while(reader.Depth != itemDepth) { 
                if(reader.Name == "artist") {
                    artist = reader.ReadString();
                } else if(reader.Name == "name") {
                    name = reader.ReadString();
                } else if (reader.Name == "url") {
                    urlLink = reader.ReadString();
                } 
                reader.Read();  
            }
            <p>Title: <a href="@urlLink">@name</a><br />Artist: @artist</p>
        }
    }
    response.Close();
} 

Notice that this code also is very similar to the code from our previous example. We simply changed it to look for the elements that we wanted to extract from our response.

Run your page by clicking the "run" button on the menu ribbon. You will see the recently played tracks listed on your Last.fm account.

This was just two examples on how you can use the Last.FM API. There are many more methods and more complex code that you can write, all you need is a little imagination!

Additional Resources

Download webmatrix http://www.microsoft.com/web/webmatrix/

Learn how to Download and Install WebMatrix http://www.microsoft.com/web/post/web-development-101-part-1-getting-started-with-webmatrix

Learn more http://www.microsoft.com/web/post/Web-Development-101-using-WebMatrix

Create a website with a WebMatrix site template http://www.microsoft.com/web/post/create-a-website-from-a-webmatrix-site-template

Publish your website http://www.microsoft.com/web/post/how-to-publish-a-web-application-using-webmatrix

Learn to download, edit and republish your website http://www.microsoft.com/web/post/download-edit-and-republish-your-website-with-webmatrix

You can discuss this article using the adjacent Facebook talkback.

For technical questions please visit our discussion forums, where we have a vibrant community of developers like you, as well as Microsoft engineers who are ready to answer your questions!