BorderLayoutBoxedLayoutOpenLayout Maximum textMedium textSmall text


Register
Friday, March 12, 2010
 English (United Kingdom) English (United States)
   
Jun 6

Written by: Gary Woodfine
06/06/2009 15:24 

I have been mucking around a lot with Last FM lately. I really rate it as a service in order to listen to music too as I code.  The other night whilst having a look around their site I came across their API’s.  I thought it would be cool to have a look around and see how I could extend the service with my own little app of sorts. Not wishing to reinvent the wheel on how to call the services – I’m a lazy programmer – I thought I would have a look at the a .net library that has been created for calling the API’s Last FM Lib.net . My initial thoughts on this was oh cool. A lot of the work has been done. Out of interest I downloaded the source code to have a look, then my thoughts turned to “Why,have they made it so difficult, and why is this code so complex?”. Although I think the work done by the author is quite good, I couldn’t help but feel a lot of it was just unnecessary and their had to be a simpler and more elegant solution.

In order to provide a simpler elegant solution I thought it would be necessary to provide some background information regarding the API’s. Last Fm state on their API overview page:

The Last.fm API allows you to call methods that respond in REST style xml.

 

What is REST?

REST stands for Representational State Transfer.  This basically means that each unique  URL is a representation of some object. You can get the contents of that object using an HTTP GET,  and have the ability to modify the object using  POST, PUT, or DELETE.  Essentially the Web is a REST system! Many of those Web services that you have been using over the past few years i.e. book-ordering services, search services, online dictionary services, etc - are REST-based Web services. Alas, you have been using REST, building REST services and you didn't even know it.

Actually, it is an architectural pattern that was first formally described by Dr. Roy Fielding in his 2000 Ph.D. dissertation at the University of California at Irvine (Fielding 2000). Dr. Fielding is a co-author, along with Sir Timothy Berners-Lee, of many of the core specifications of the World Wide Web, and a co-founder of the Apache Foundation. In his dissertation, he was attempting to describe the architecture of an application for using the World Wide Web, and, as he himself points out, “the most common example [of such an application] is a Web browser” (Fielding 2000). So, Dr. Fielding was not proposing a way of building web services; he was providing a formal description of the architecture of a web browser.

No standards just style

REST is not a standard, It is rather an architectural style.  There is no worldwide body governing how to create REST web services. There are however standards that a REST web services are able to use, these standards include:

  • HTTP
  • URL
  • XML/HTML/GIF/JPEG/etc (Resource Representations)
  • text/xml, text/html, image/gif, image/jpeg, etc (MIME Types)

 

Should I use SOAP or have a REST?

Every time some Web application service provider comes up with a Web services API that allows developers to integrate with their services, a lot of attention is paid to the interaction design pattern implemented by the API. If the API uses the REST-style interaction, proponents of the REST approach laud the API as a grand example of why REST-style services are far superior to SOAP-style services; likewise if the API uses a SOAP style Web service pattern. Little attention seems to be paid to the fact that the choice of pattern depends largely on the type of application being implemented and, like all good architectural decisions, developers should base their choice on the specific technical needs and characteristics of the application being developed rather than on some particular affinity towards a single architectural approach.

At a fundamental level, the difference between REST-style and SOAP-style Web services hinges on whether or not an application is resource-oriented or activity-oriented.

 

Calling REST Web service

In Essence calling a RESTful service is, more or less, imitating a classic web Request/Response, as the following code sample indicates.

        HttpWebRequest request = WebRequest.Create("http://www.threenine.co.uk") as HttpWebRequest;
         // Get response   
         using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
         {
             // Get the response stream   
             StreamReader reader = new StreamReader(response.GetResponseStream());

             // Console application output   
             Console.WriteLine(reader.ReadToEnd());
         }
         Console.Read();
The code above makes a web request and receives the response and then writes the data out to the console window.  This in essence display’s the type of approach that can be used to call a REST service.  

A REST service is one that responds to an HTTP request with a plain text document. The request method together with the query string determines the content of the response document.

REST and XML

A natural format for the plain text documents provided by web services is XML. Typically, those XML documents are not in the SOAP format. The term Plain Old XML or POX is sometimes used to refer to XML messages that are not in the SOAP format. 

Calling Last FM service

In this example I will be calling the Track.GetTopTags, as the documentation points out the service has several arguments that need to be passed and the response is an XML file.  The easiest way to call a RESTful service is by typing the query into a web browser. 

If you try typing :

http://ws.audioscrobbler.com/2.0/?api_key=[Enter Your API key Here]&artist=metallica&method=track.gettoptags&track=one

The browser will respond with the XML :

I could find any schema definitions for the XML files, so I created my own, this is simple to do as you pre my previous post . The xml File returned from the LastFm service will look like the following:

<lfm status="">
  <toptags artist="" track="">
      <tag>
        <name></name>
        <count></count>
        <url></url>
      </tag>
    </toptags>
</lfm>

 

From the XML file we are able  to derive that it will adhere to the following schema:

<?xmlversion="1.0" encoding="utf-8"?>
<
xs:schemaattributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <
xs:elementname="lfm">
    <
xs:complexType>
      <
xs:sequence>
        <
xs:elementname="toptags">
          <
xs:complexType>
            <
xs:sequence>
              <
xs:elementminOccurs="0" maxOccurs="unbounded" name="tag">
                <
xs:complexType>
                  <
xs:sequence>
                    <
xs:elementname="name" type="xs:string/>
                    <
xs:elementname="count" type="xs:string" />
                    <
xs:elementname="url" type="xs:string" />
                  </
xs:sequence>
                </
xs:complexType>
              </
xs:element>
            </
xs:sequence>
            <
xs:attributename="artist" type="xs:string" use="required" />
            <
xs:attributename="track" type="xs:string" use="required" />
          </
xs:complexType>
        </
xs:element>
      </
xs:sequence>
      <
xs:attribute name="status" type="xs:string" use="required" />
    </
xs:complexType>
  </
xs:element>
</
xs:schema>

The Service also requires several parameters , because of the fact that a REST service operates in the same manner as a normal web request ,can be sent in the query string.

In the code sample below I created a class using the xsd tool , then I have just simply serialised the response from the web service. 

HttpWebRequest request = WebRequest.Create("http://ws.audioscrobbler.com/2.0/?api_key=[Put your API Key Here]&artist=metallica&method=track.gettoptags&track=one") as HttpWebRequest;
          using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
          {
              XmlSerializer serializer = new XmlSerializer(typeof(lfm));
              XmlReaderSettings settings = new XmlReaderSettings();
              settings.ValidationFlags = XmlSchemaValidationFlags.None;
              settings.ValidationType = ValidationType.None;
              settings.ConformanceLevel = ConformanceLevel.Auto;
              settings.IgnoreProcessingInstructions = true;
              XmlReader reader = XmlReader.Create(response.GetResponseStream(), settings);
              lfm p = (lfm)serializer.Deserialize(reader);
              

              foreach (lfmToptagsTag tag in p.toptags)
              {
                  
                  Console.WriteLine("Tag name: {0}  , Count: {1} , url: {2}", tag.name,tag.count,tag.url);
              }
           
          }
          Console.Read();

 

 

Useful Resources

Last FM API Introduction

Wikipedia

Create XML Schema's in Visual Studio

Tags:

Your name:
Your email:
(Optional) Email used only to show Gravatar.
Your website:
Title:
Comment:
Security Code
Enter the code shown above in the box below
Add Comment   Cancel 


Copyright 2010 by Three Nine Consulting