Python: Last.fm Simple API Example


/ Published in: ActionScript 3
Save to your folder(s)

Recently I needed to capture a JSON feed of the top artists from Last.fm. The script makes a request for a JSON response which I later treat as a dictionary object. You'll probably need to sign up for an API Key before using this script


Copy this code and paste it in your HTML
  1. import urllib, urllib2
  2. try:
  3. import json
  4. except ImportError:
  5. import simplejson as json
  6.  
  7. class LastFM:
  8. def __init__(self ):
  9. self.API_URL = "http://ws.audioscrobbler.com/2.0/"
  10. self.API_KEY = "API_KEY_FROM_LAST_FM"
  11.  
  12. def get_genre(self, genre, **kwargs):
  13. kwargs.update({
  14. "method": "tag.gettopartists",
  15. "tag": genre,
  16. "api_key": self.API_KEY,
  17. "limit": 3,
  18. "format": "json"
  19. })
  20. try:
  21. #Create an API Request
  22. url = self.API_URL + "?" + urllib.urlencode(kwargs)
  23. #Send Request and Collect it
  24. data = urllib2.urlopen( url )
  25. #Print it
  26. response_data = json.load( data )
  27. print response_data['topartists']['artist'][0]['name']
  28. #Close connection
  29. data.close()
  30. except urllib2.HTTPError, e:
  31. print "HTTP error: %d" % e.code
  32. except urllib2.URLError, e:
  33. print "Network error: %s" % e.reason.args[1]
  34.  
  35. def main():
  36. last_request = LastFM()
  37. last_request.get_genre( "rock" )
  38.  
  39. if __name__ == "__main__": main()

URL: http://www.last.fm/api

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.