|
Examples of LazyTune API's clients
All the following examples are distributed under the very liberal BSD licence so that you will be able to use and modify it freely. A Python client
This is a very simple Python example around the LazyTune REST API as documented on http://lazytune.com/api/This example uses the XML format offered by the API. Usage examples :
LTClient = LazyTuneClient('YOUR_API_KEY') #!/usr/bin/python ''' This is a very simple Python example around the LazyTune.com REST API as documented on http://lazytune.com/api/ You will have to register an API key in order to use it. Usage examples : LTClient = LazyTuneClient('YOUR_API_KEY') print LTClient.call('artist', 'search', 'pete rock', ['pict','mbid']) print LTClient.call('song', 'search', 'green day', [], 1) print LTClient.call('album', 'id', 'LDQMzS') Author: Florent Weber Copyright (c) 2007, 2008 LazyTune Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of California, Berkeley nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ''' from xml.dom import minidom from urllib2 import urlopen import urllib class LazyTuneClient(object): ''' This class abstracts LazyTune's API queries ''' API_BASE_URL = 'http://api.lazytune.com/1.0' def __init__(self, APIKey): self.APIKey = APIKey @staticmethod def xml_dom_get_text(node): ''' This method extracts XML text data from a given node. ''' result = [] for child in node.childNodes: if child.nodeType == child.TEXT_NODE: result.append(child.data) return ''.join(result) def xml_dom_node_to_dict(self, node): ''' This method turns a DOM element into a dict. ''' result = {} for child in node.childNodes: if child.nodeType == child.ELEMENT_NODE: if child.tagName == 'artist' or child.tagName == 'album': result[child.tagName] = self.xml_dom_node_to_dict(child) else: result[child.tagName] = self.xml_dom_get_text(child) return result def buildURL(self, collection, method, value, options = '', limit = 0): ''' Build LazyTune's query URL (limit=0 means maximum default limit) ''' if len(options): args = 'options=%s&key=%s' % (options, self.APIKey) else: args = 'key=%s' % (self.APIKey) if limit: args += '&limit=%s' % (limit) value = urllib.quote(value) return '%s/%s/%s/%s.xml?%s' % (self.API_BASE_URL, collection, method, value, args) def call(self, collection, method, value, options = [], limit = 0): ''' This method performs the HTTP request and returns the parsed XML data ''' if len(options): url = self.buildURL(collection, method, value, ','.join(options), limit) else: url = self.buildURL(collection, method, value, [], limit) try: xmlData = urlopen(url).read() except: print 'Error while performing GET HTTP request :', url return None try: dom = minidom.parseString(xmlData) print 'Error while parsing XML data' return None try: ans = dom.getElementsByTagName('error')[0] print 'LazyTune API error :', ans.firstChild.nodeValue return None except: pass collectionElements = dom.getElementsByTagName(collection) if len(collectionElements): result = [] for element in collectionElements: result.append(self.xml_dom_node_to_dict(element)) return result return result A PHP5 client
This is a very simple PHP5 example around the LazyTune REST API as documented on http://lazytune.com/api/This example uses the Serialized PHP format offered by the API. Usage examples :
$LTClient = new LazyTuneClient ('YOUR_API_KEY') ; <?php /** This is a very simple PHP5 example around the LazyTune.com REST API as documented on http://lazytune.com/api/ You will have to register an API key in order to use it. Usage examples : $LTClient = new LazyTuneClient ('YOUR_API_KEY') ; print_r ($LTClient->call ('artist', 'search', 'pete rock', array('pict', 'mbid'))) ; print_r ($LTClient->call ('song', 'search', 'green day', array(), 1)) ; print_r ($LTClient->call ('album', 'id', 'LDQMzS')) ; Author: Florent Weber Copyright (c) 2007, 2008 LazyTune Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of California, Berkeley nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** This class abstracts LazyTune's API queries */ class LazyTuneClient { private $API_BASE_URL = 'http://api.lazytune.com/1.0' ; function __construct ($APIKey) { $this->APIKey = $APIKey ; } /** Builds the query URL */ private function buildURL ($collection, $method, $value, $options = '', $limit = 0) { $args = '' ; if (empty ($options)) $args = 'key='.$this->APIKey ; else $args = 'options='.$options.'&key='.$this->APIKey ; if ($limit) $args .= '&limit='.$limit ; $value = urlencode ($value) ; return sprintf ('%s/%s/%s/%s.php?%s', $this->API_BASE_URL, $collection, $method, $value, $args) ; } /** Perform a HTTP query and unserialize the answered data */ public function call ($collection, $method, $value, $options = array(), $limit = 0) { $args = '' ; if (count ($options)) $url = $this->buildURL ($collection, $method, $value, implode(',', $options), $limit) ; else $url = $this->buildURL ($collection, $method, $value, '', $limit) ; if (!($phpData = file_get_contents ($url))) { echo 'Error while performing GET HTTP request : '.$url."\n" ; return NULL ; } if (!($data = unserialize ($phpData))) { echo 'Error while unserializing result'."\n" ; return NULL ; } if (isset($data['error'])) { echo 'LazyTune API error : '.$data['error']."\n" ; return NULL ; } return $data ; } } ?> A Perl client
This is a very simple Perl example around the LazyTune REST API as documented on http://lazytune.com/api/This example uses the XML format offered by the API, so you will have to install the XML::Simple module :
$ perl -MCPAN -e shell
$LTClient = new LazyTuneClient ('YOUR_API_KEY') ; $ perl -MXML::Simple -MLWP::Simple LazyTuneClient.pl See Perl source code#!/usr/bin/perl # This is a very simple Perl example around the LazyTune.com REST API as # documented on http://lazytune.com/api/ # You will have to register an API key in order to use it. # # Usage examples : # # $LTClient = new LazyTuneClient ('YOUR_API_KEY') ; # print Dumper($LTClient->call('artist', 'search', 'pete rock', 'pict,mbid', 0)) ; # print Dumper($LTClient->call('song', 'search', 'green day', '', 1)) ; # print Dumper($LTClient->call('album', 'id', 'LDQMzS', '', 0)) ; # # Author: Florent Weber # Copyright (c) 2007, 2008 LazyTune # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the University of California, Berkeley nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # This package abstracts LazyTune's API queries package LazyTuneClient ; sub new { my ($class, $APIKey) = @_ ; my $self = { '_APIKey' => $APIKey, '_API_BASE_URL' => 'http://api.lazytune.com/1.0' } ; bless $self, 'LazyTuneClient' ; return $self ; } # Build LazyTune's query URL (limit=0 means maximum default limit) sub buildURL { my ($class, $collection, $method, $value, $options, $limit) = @_ ; my $self=shift ; if (length($options)) { $args = 'options='.$options.'&key='.$self->{'_APIKey'} ; } else { $args = 'key='.$self->{'_APIKey'} ; } if ($limit) { $args .= '&limit='.$limit ; } # URLEncode voodoo $value =~ s/([^A-Za-z0-9])/sprintf("%%%02X", ord($1))/seg ; return $self->{'_API_BASE_URL'}.'/'.$collection.'/'.$method.'/'.$value.'.xml?'.$args ; } # This method performs the HTTP request and returns the parsed XML data sub call { use XML::Simple ; use LWP::Simple ; use Data::Dumper ; my ($class, $collection, $method, $value, $options, $limit) = @_ ; my $self=shift ; $url = $self->buildURL($collection, $method, $value, $options, $limit) ; my $XMLData = get $url ; $xml = new XML::Simple ; $data = $xml->XMLin($XMLData) ; if (length($data->{'error'})) { print 'LazyTune API error : '.$data->{'error'}."\n" ; return ; } return $data ; } 1; A Java client
This is a very simple Java example around the LazyTune REST API as documented on http://lazytune.com/api/This example uses the JSON format offered by the API through the JSON Java library that could be found on http://www.json.org/java/ To use this example you will have to install it. Usage examples :
public static void main ( String[] args ) throws IOException, JSONException /** This is a very simple Java example around the LazyTune.com REST API as documented on http://lazytune.com/api/ This class uses the JSON format offered by the API through the JSON Java library that could be found on http://www.json.org/java/ You will have to register an API key in order to use it. Usage example : public static void main ( String[] args ) throws IOException, JSONException { JSONObject json ; String [] options = {"mbid", "pict"} ; LazyTuneClient LTClient = new LazyTuneClient ("YOUR_API_KEY") ; json = LTClient.call("artist", "search", "pete rock", options, 1) ; if (json == null) return ; System.out.println(json.get("artist")) ; } Author: Florent Weber Copyright (c) 2007, 2008 LazyTune Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of California, Berkeley nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import java.net.* ; import java.io.* ; import org.json.JSONObject ; /** This really simple client abstracts LazyTune's API queries */ public class LazyTuneClient { private String APIKey ; private static String BASE_API_URL = "http://api.lazytune.com/1.0" ; public LazyTuneClient (String APIKey) { this.APIKey = APIKey ; } /** This silly method build the query URL */ private String buildURL (String collection, String method, String value, String options, int limit) { String args ; if (options.equals("")) args = "key="+this.APIKey ; else args = "options="+options+"&key="+this.APIKey ; if (limit > 0) args += "&limit="+limit ; try { value = URLEncoder.encode(value, "UTF-8") ; } catch (UnsupportedEncodingException e) { e.printStackTrace() ; } return LazyTuneClient.BASE_API_URL+"/"+collection+"/"+method+"/"+value+".json?"+args ; } /** This method perform the HTTP GET request and parses the given result using a JSONObject */ public JSONObject call (String collection, String method, String value, String [] options, int limit) { URL url ; String str, data; JSONObject json ; int l = options.length ; try { if (l > 0) { String opt = new String(options[0]) ; for (int i = 1; i<l; i++) opt += ","+options[i] ; url = new URL(this.buildURL(collection, method, value, opt, limit)) ; } else url = new URL(this.buildURL(collection, method, value, "", limit)) ; BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); data = "" ; while ((str = in.readLine()) != null) data += str ; json = new JSONObject(data); try { /* If there's no "error" key, it will fail */ String err = (String) json.get("error") ; if (err.length() > 0) { System.err.println("LazyTune API error : "+err) ; in.close() ; return null ; } } catch (JSONException e) {} ; in.close() ; return json ; } catch (MalformedURLException e) { /* Should never happen */ System.err.println("URL Error") ; return null ; } catch (IOException e) { System.err.println("HTTP Error") ; return null ; } catch (JSONException e) { System.err.println("JSON Error") ; return null ; } } } |
