Return to Snippet

Revision: 55470
at February 8, 2012 06:19 by chrisaiv


Initial Code
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()

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

Initial Description
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

Initial Title
Python: Last.fm Simple API Example

Initial Tags
python

Initial Language
ActionScript 3