/ Published in: ActionScript 3

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
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
import urllib, urllib2 try: import json except ImportError: import simplejson as json class LastFM: def __init__(self ): self.API_URL = "http://ws.audioscrobbler.com/2.0/" self.API_KEY = "API_KEY_FROM_LAST_FM" def get_genre(self, genre, **kwargs): kwargs.update({ "method": "tag.gettopartists", "tag": genre, "api_key": self.API_KEY, "limit": 3, "format": "json" }) try: #Create an API Request url = self.API_URL + "?" + urllib.urlencode(kwargs) #Send Request and Collect it data = urllib2.urlopen( url ) #Print it response_data = json.load( data ) print response_data['topartists']['artist'][0]['name'] #Close connection data.close() except urllib2.HTTPError, e: print "HTTP error: %d" % e.code except urllib2.URLError, e: print "Network error: %s" % e.reason.args[1] def main(): last_request = LastFM() last_request.get_genre( "rock" ) if __name__ == "__main__": main()
Comments
