Return to Snippet

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

Initial Code
import urllib, urllib2
    import json
except ImportError:
    import simplejson as json

class LastFM:
    def __init__(self ):
        self.API_URL = ""
        self.API_KEY = "API_KEY_FROM_LAST_FM"

    def get_genre(self, genre, **kwargs):
            "method":	"tag.gettopartists",
            "tag":		genre,
            "api_key":	self.API_KEY,
            "limit":	3,
            "format":	"json"
            #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
        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

Initial Description
Recently I needed to capture a JSON feed of the top artists from  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: Simple API Example

Initial Tags

Initial Language
ActionScript 3