Skip to content

Instantly share code, notes, and snippets.

@chrisbrasington
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisbrasington/984ec578e9e8248466e5 to your computer and use it in GitHub Desktop.
Save chrisbrasington/984ec578e9e8248466e5 to your computer and use it in GitHub Desktop.
last.FM API call building

last.FM API call building with parameters

I wanted a way to call the last.FM API with little hassle. Any function, any callback, and less I had to deal with AJAX syntax the better. I implemented a calling method to build out a request URL from parameters given, and also set the successfull callback to handle the method.

In this example I'm calling user.getRecentTracks.

This type of request building works for all function calls.

Note: that a "Successful" callback will be hit for both receiving the data you desire as well as an invalid response from the API such as "that method did not exist" or "missing parameters". Trickier to handle, means you either need to ensure your parameters/call works, or handle a scenario of always getting an "error" JSON object from last.fm in a successful callback. An AJAX ERROR callback means you got no response from last.FM, it's different.

// invoke call for user's recent tracks
call({ method:'user.getRecentTracks',
user: 'raylinth',
limit: 20},
recentTracksCallback
);
// build url for API call
function call(params, callback) {
// build base url
url = 'http://ws.audioscrobbler.com/2.0/?'
url += '&format=json'
// API key is not passed in, and is stored elsewhere
url += 'api_key='+key.lastfm
// build dynamic part of api call
for(p in params) {
url += '&'+p+'='+params[p]
}
// make an ajax, asynchronous call
getJSON(url,callback)
}
// generic JSON request and callbacks
function getJSON(url, callback) {
$.ajax({
url: url,
type: "get",
crossDomain: true,
dataType: 'json',
success: function(data){
if(typeof(callBack) =='function')
callBack(data)
else
{
console.log('received data, but no callback specified')
console.log(data)
}
},
error: function(r) {
log('retrieve JSON - failure')
}
});
}
// don't forget you need to have defined the callback!
// if you don't, this will try to call a non-existant function
function recentTracksCallback(data) {
console.log("received user's recent tracks");
// parse and do things with data
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment