Requesting Webservices in Flex 3

Follows Webservices, simple introduction.

In Flex 3 requesting data is really simple, since you really have to load a well know url which prints out XML (or JSON or whatever).

I assume you have read the introduction, here we are with a url that prints out informations about Cher’s top fans:

http://ws.audioscrobbler.com/2.0/?method=artist.gettopfans&artist=cher&api_key=xxxxxxxxxxxx

What we have to do is load that url with a mx:HTTPService Object and parse the result as XML. Simple, it isn’t?

First: create the HTTPService object:

<mx :HTTPService id="fetchData" url="{apiUrl}"  resultFormat="xml" result="handler(event)" fault="error(event)"/>

and the handlers

private function handler(event:ResultEvent):void {
xmldata = XML(event.result);
}
private function error(event:FaultEvent):void {
Alert.show("Error: " + event.fault.message);
}

And oplà, in the data field you will have the returned xml, ready to be shown in your preferred component!

Webservices, simple introduction.

Website exposes their data to 3rd part application trought webservices and xml. It’s pretty simple: the user calls a url which has some parameters that contains the request, the webserver handles the request, queries the database and prints out the resulting data in XML (or JSON, or other) format. This permits to limit user access to the complete data, exposing only a part of them.

This is the underlying technology that empowers all kinds of mashup: you request data from some sources, combine it and show them up in your application. I want to share some examples of building an app that works with data loaded from external webservices; I’m not gonna show you another flickr example, there are too many out there, so I’d prefer doing something using Last.fm APIs.

First thing is, you have to apply for an API KEY. What does this means? Api calls somethines aren’t free, other times the provider wants to keep track of who calls which api, or keep statistics; So you have register a unique id that will sign all your calls. Usually you pass this key as a parameter of the function.

So to start, let’s choose a simple function to call, artist.getTopFans sounds good and doesn’t require authentication. It prints out informations about the top fans of a given artist. The documentation page tells that it requires 2 parameters: the artist name, and the api key, they explains themselves.

So now we know that we want to know who are the top fans of.. let’s say, Cher. We have to take the root url of the APIs, which is

 

http://ws.audioscrobbler.com/2.0/

 

enqueued by the parameters written as &key=value pairs (It’s a simple HTTP GET request, other services will require HTTP POST requests, but, later).
We now have the url of the call, which should be similar to:

 

http://ws.audioscrobbler.com/2.0/?method=artist.gettopfans&amp;artist=cher&amp;api_key=xxxxxxxxxxxx

You can try substituting your api key and open that url in a web browser.