3

I'm trying to learn how to properly use AJAX and RESTful APIs, and while I get the idea, the actual implementation of things like authenticating is kind of baffling me. What's particularly frustrating is that none of the documentation on sites like Last.FM or TVRage.com actually lay out code examples, which I feel like would help me a ton.

If anyone's used the Last.FM API particularly and could give a quick code example -- for any of their methods -- I'd really appreciate it.

Right now, I'm trying to authenticate myself, according to their instructions.

Construct your api method signatures by first ordering all the parameters sent in your call alphabetically by parameter name and concatenating them into one string using a <name><value> scheme.

A <name><value> scheme? Like, <apikey><keyitself>? And then what do I do when authenticated, somehow store a session for an hour and then refresh, or authenticate on every call? I just don't get the specifics of how to actually implement it...

GreenTriangle
  • 2,382
  • 2
  • 21
  • 35

1 Answers1

8

If you look at the API docs, you will see a list of methods on the left hand navigation menu (let's take artist.getInfo in this example - http://www.last.fm/api/show/artist.getInfo).

Now, in order to make the call, you will need to make an AJAX request to the restful web service, which will then either return you a XML or JSON response. To test this out, you can build a query up and see the response.

http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=After+The+Burial&api_key=57ee3318536b23ee81d6b27e36997cde&format=json

If you try this link, you will see a JSON representation of the data. If you view the API link provided at the very start of my answer, you can start to experiment with some of the optional parameters too. The next issue to tackle is how to make the AJAX call itself.

If you follow this guide, it will show you both the JavaScript and jQuery methods of making an AJAX call How to make an AJAX call without jQuery?. In my example we will make a POST request method using the same parameters detailed above:

$.ajax({
    type : 'POST',
    url : 'http://ws.audioscrobbler.com/2.0/',
    data : 'method=artist.getinfo&' +
           'artist=After+The+Burial&' +
           'api_key=57ee3318536b23ee81d6b27e36997cde&' +
           'format=json',
    dataType : 'jsonp',
    success : function(data) {
        // Handle success code here
    },
    error : function(code, message){
        // Handle error here
    }
});

When you hit the success callback, the 'data' parameter represents the JSON response that has been parsed as a JavaScript object.

Here is a jsfiddle I have made that demonstrates the implementation of a web service call to last.fm:

http://jsfiddle.net/zvsrF/6/

Just make sure to get your own API key, and refactor the success callback to be a lot more graceful than my example.

Community
  • 1
  • 1
HarbyUK
  • 386
  • 1
  • 5