Writing a Flash Lite Client for a REST API

This tutorial explains how to create a flash REST API client that works with Actionscript 2 and Flash Lite 3.1+. Its not as simple as you might think, but the most complex part is knowing and understanding all the restrictions, many of which I’ve outlaid here.

API restrictions

Unfortunately there are some restrictions within Flash Lite which means you will only be able to access certain API’s. Before continuing, ensure the API you are trying to access meets the following criteria. If its your API, you are in luck, you can fix these issues.

Crossdomain Policy

You will need to be accessing an API which has a crossdomain policy file in place. If you own the API you can create one. If not you will need to create a proxy – although that’s out of scope of this tutorial.

Authentication

Flash Lite does not work with HTTP header based security using the “Authorize” header. The function for adjusting headers – XML.addRequestHeader has a bug. In addition, you cannot use the addRequestHeader feature unless you are making a POST request, bug or no bug. This means for GET request you need to find another way of authenticating anyway. If the API you have access to doesn’t allow any other means of authentication, you won’t be able to write a Flash Lite client.

If you have control of the API, ensure it can read the user credentials from the URL for GET requests, and from either the URL or parameter body for POST requests. That way you can avoid having to use addRequestHeader.

HTTP Status codes

Flash can’t easily interpret HTTP status codes. The API should therefore have an option for returning status in either an XML or string format. The HTTP status should always be 200, with the actual success code returned in the body of the content. This code can then be interpreted by Flash.

Please note, for POST’s, the status returned should be of the same type (either XML or string) as the data posted. So in other words if you pass XML to the API to POST data, the status should be returned as XML, if you pass name key pairs to POST data, the status should be returned as a plain text name key pair (e.g. name=xxxx). If the API interprets POSTed data in chunks of XML, it should return the status as XML. This enables you to use either XML.sendAndLoad to send and read XML or LoadVars.sendAndLoad to send and read variables. You can’t (as far as I can tell) send XML and read variables, or send variables and read XML.

PUT and DELETE

You can’t make PUT and DELETE requests from Flash (or indeed any browser), so you will need to ensure your API uses overloaded POST. That is, you can specify the PUT or DELETE method in the POST url and the API interprets it, or you can make edits and deletes through the basic POST or GET functions.

Flash Lite checklist

You will need to make a few updates to your app before connecting to the API.

Playback settings

Ensure you have set the playback settings to access network only (File in top menu -> Publish Settings option -> Flash tab -> Advanced section -> Local playback security dropdown -> set to Access network only)

Device central

Ensure you have selected a Flash Lite 3.1 device in Device Central for testing.

Ensure under the device central security settings you have selected “Local Trusted Sandbox”.

Flash Lite security settings

When testing on a device as a swf, if you find network errors, ensure the swf is placed inside the Flash Lite trusted folder, if available. Location of the trusted folder will vary from device to device, but for Nokia’s N95 its located in C:/Data/Others/Trusted. Note that the Others folder may appear as Other without the s – this is not an issue. If you can’t find the Trusted folder inside Other(s), create it. To access the swf from the device just navigate directly to C:/Other(s), the data folder won’t appear within the phone view. There’s more on this topic on Kuneri Bloggy.

Making a GET request

To perform a GET request, returning XML you use the XML.load method.

var my_xml:XML = new XML();

my_xml.onLoad = function(success:Boolean) {

    var endTime:Number = getTimer();

    var elapsedTime:Number = endTime-startTime;
   
    if (success) {
            trace("xmlDecl:"+my_xml.xmlDecl);
            trace("contentType:"+my_xml.contentType);
            trace("docTypeDecl:"+my_xml.docTypeDecl);
            trace("packet:"+my_xml.toString());
    } else {
            trace("Unable to load remote XML.");
    }

    trace("loaded in: "+elapsedTime+" ms.");

};
my_xml.load("http://api.url.com/user/1.xml");

You get the idea, you could create a text field to output the data on the device, manipulate the xml etc.

To perform a GET request returning name value pairs, you use the LoadVars.load method.

var myLoadVars:LoadVars = new LoadVars();
myLoadVars.onLoad = function(success:Boolean) {
    if (success) {
        trace(this.toString());
    } else {
        trace("Error loading/parsing LoadVars.");
    }
};
myLoadVars.load("http://api.url.com/user/1.json");

POST request

To make a POST request by sending name value pairs and processing a returned status code in name value format, you use the LoadVars.sendAndLoad method.

In this example we are posting a name value pair of “name=New Category”, with the server interpreting the field name, and returning either “error=404″ or “status=200″ as plain text output. The code interprets either the error or the status and traces it out to the console. You would probably interpret it in some way and do something more with it.

var resultLoadVars:LoadVars = new LoadVars();
resultLoadVars.onLoad = function(success:Boolean) {
        if (success) {
                if (resultLoadVars.error !== undefined) {
                trace("error: "+result_lv.error);                                      
                }
                if (resultLoadVars.status !== undefined) {
                trace("status: "+result_lv.status);                                    
                }
        } else {
        trace("Error connecting to server.");
        }
};
var send_lv:LoadVars = new LoadVars();
send_lv.name = "New Category";
send_lv.sendAndLoad("http://api.url.com/user/1", result_lv, "POST");

To make a POST request by sending XML and processing a returned status code in XML format, you use the XML.sendAndLoad method.

In this example we are posting xml containing the tag name with content “New Category”, with the server interpreting the field name, and returning either an error tag with the code “404″ or a status tag with the code “200″ as XML. The code interprets either the error or the status and traces it out to the console. You would probably interpret it in some way and do something more with it.

var dataToPost:String = "<name>New Category</name>";
var my_xml:XML = new XML(dataToPost);
var myReply_xml:XML = new XML();
myReply_xml.ignoreWhite = true;
myReply_xml.onLoad = myOnLoad;
my_xml.sendAndLoad("http://api.url.com/user/1", myReply_xml);
function myOnLoad(success:Boolean) {
    if (success) {
        if ((myReply_xml.firstChild.nodeName == "error")) {
            trace("error: "+myReply_xml.firstChild);
        }
        if ((myReply_xml.firstChild.nodeName == "status")) {
            trace("status: "+myReply_xml.firstChild);
        }        
    } else {
       trace("Error connecting to server.");
    }
}

Next steps

Don’t worry too much about following the code examples here, follow the links to the adobe documentation and see if you can get the code to work with the API you have. I’m starting out in this area too – so have really just presented my initial findings after a couple of days research – hopefully this will save some of you that time at least! Leave issues or problems with specific devices, links to better ways of doing things or suggestions in the comments.

1 Comment

jigish thakar

hi i am building one flash lite application.. which will interact with my API..
my API gives response in JSON string..

everything works fine till the result has limit of 10 records, but when it exceeds 15 records. json parser stops working.
now here the scenario is to download the json on first request itself and then manipulating that json i show run my application…

i am stucked in between, need solution on this. thanks in adv

Leave a comment: