Home >
REST and Flex
In this tutorial we start to work with REST and Flex, are you asking what is and why use REST?
REST is acronym for REpresentational State Transfer, and it helps you to provide services to communicate with your database via XML but not only. With REST you can work in large web applications to small RIAs, in fact it is a scalable system that makes all communication easier.
Another good thing about REST is that divides the goals of client side and server side functionality, so you can work in a parallel way and choose your favorite client side or server side technology to develop an application. It's also very useful if you'd like to create your GUI with different technologies like AJAX or Flex, but still reuse the same services to communicate with database. REST is based on HTTP headers, in fact all communications from client to server side pass through HTTP headers like POST, GET, PUT, and DELETE.
This is very interesting because you can create, read, update or delete (CRUD) a record by only calling a specific path and by setting the correct header. REST uses token authentication to have a safe way to communicate with you RIA or website, with a token you can prevent other websites or applications from calling your service.
If you are a Flex developer you know very well that Flex doesn't support some HTTP headers like PUT or DELETE, so we will work with a free library called as3httpclientlib that uses a workaround using sockets to solve this Flex issue.
BEFORE STARTING TO CODE
Before starting with this tutorial you must download and configure your computer to work with Rails and Flex 4; if your computer is already configured please skip to the next paragraph.
If you are running Mac OS X, you have Ruby preinstalled, if you have Windows OS, you must download Ruby from http://rubyforge.org/frs/?group_id=167 and install it.
If you'd like test to see if Ruby is installed on your Operating System, type ruby -v at command prompt, if you get command not found, you will need to download and install.
Once Ruby is installed you can download Rubygems which helps you to download and install all Ruby modules in a very quick and easy way. After installing RubyGems you can download Rails, Mongrel and SQLite with the following lines of code in your terminal on Mac OS X, or command prompt if you work in Windows:
for RAILS:
sudo gem install rails
for Mongrel:
gem install Mongrel
for SQLite:
gem install sqlite3-ruby
So now a little overview of the last few steps.
Rails is the server side technology that I choose to create interaction through database and REST, in fact with Rails we create all methods to provide REST services to the client. Why Rails? Because I think is so easy to start working with with and it's an OOP language, so you can use same concepts learned in Actionscript 3 to retrieve in Rails.
Mongrel is an HTTP server where your Rails applications runs, you can learn more about Mongrel at Mongrel's website.
Finally SQLite is a free database that is very fast to work with it, it's also the same that you can find embedded within Adobe AIR. A key SQLite feature is that you have only 1 file for database so you can move your data with a simple drag and drop to another computer or mobile device. Fortunately, it's not so "lite" like the name suggests, in fact a SQLite database can store until to 4GB of data; for more information about SQLite's limits take a look at sqlite.org. I suggest you download the SQLite Database browser to use during this tutorial, it's a free and very easy to use application that you can find here.
Finally you can decide which Ruby IDE you'd like to install in your computer; you can choose between Aptana standalone or plugin for eclipse, TextMate if you use Mac OS X or Ruby in Steel for Visual Studio (this one isn't open-source) if you have Win OS.
For the client side you must download Flash Builder BETA (standalone or eclipse plugin), that you can find at labs.adobe.com. Then you should download as3httpclientlib to work with REST, this library also depends on then as3crypto library.
download as3crypto
download as3corelib
As3crypto is a really good library for encrypting and decrypting string data, I usually use this library to create login form with Flash or Flex because you can send encrypted data to server side script; as3corelib is one of the most popular AS3 library. It includes many utilities, like a JSON serialization API, Image encoders, String and Number utils and so on. Both libraries are used in as3httpclientlib to solve Flex problem to work with DELETE and PUT headers.
After you have downloaded all files we are ready to start. During this tutorial you will make an address book with REST and Flex.
RAILS PART
When I approach Rails for the first time I was really impressed with this language because is very easy to write and also it's very powerful.
This first step is to create database and all methods to provide REST services.
Open your Terminal or Command Prompt, create and set your project folder and run these lines of code:
rails rails
cd rails
rake db:create:all
./script/generate scaffold AddressBook firstname:String surname:String role:String description:Text company:String
rake db:migrate
With those few lines of code you have just created everything you need to work with flex, that's cool, isn't it?!
Now you must make some changes on your Rails code to solve some possible problems that you can find during development. But first of all give me opportunity to explain those 5 lines of code.
With the first line, you created a "skeleton" of your Rails application, in fact you can find the folder that you choose to install rails files.

The second line of code allowed you to enter in rails folder, the third one created your database environment, in particular creates 3 databases, one for development scope, one for production and one for test.
Rake is an utility for ruby that contains a library of prepackaged tasks that users can use to automate Ruby work; more information on rake is available at http://rake.rubyforge.org/.
In this case you used Rake to create the databases, if you prefer you could create it in visual mode the using SQLite Database browser that I mentioned earlier, you can download it from sourceforge.
In the script folder you call generate scaffold to create an MVC architecture in Rails that allows you to create REST access to the databases, scaffolding is a method used to build database-backed software applications and it works with certain frameworks; in this case using Ruby you create everything with a scaffold generation that create all you need to interact with the database.
The last line of code migrates from the model to the SQLite development database; if you are interesting to see how Rails make this, take a look at temp file in the rails>db>migrate folder.
Now test your configurations by typing this line of code in your Terminal or Command Prompt:
./script/server
When you press the Enter key, you turn on Mongrel and you can easily test it by opening your web browser and going to http://localhost:3000/ if everything is ok you should see something like this:
If you Mongrel is running go, ahead and start to change some lines of code in Rails.
First of all open address_books_controller.rb that you find in rails>app>controllers folder, modify the create function so that it returns all data from database:
def create
@address_book = AddressBook.<span class="category1">new</span>(params[:address_book])
respond_to <span class="category1">do</span> |format|
<span class="category1">if</span> @address_book.save
flash[:notice] = '<span class="quote">AddressBook was successfully created.</span>'
@finalData = AddressBook.all
format.xml { render :xml => @finalData.to_xml(:dasherize => <span class="category1">false</span>) }
<span class="category1">else</span>
format.xml { render :xml => @address_book.errors, :<span class="category2">status</span> => :unprocessable_entity }
end
end
end
Finally modify all to_xml method with :dasherize => false like this example:
format.xml { render :xml => @address_books.to_xml(:dasherize => false ) }
This modify is important if you want to work with Flex or Flash because they don't work with XML nodes with dashes so this boolean needs to convert each dash symbol to underscore.
The last change on Rails side is to open the other controller called application_controller.rb in the same folder, and comment out protect_from_forgery and add self.allow_forgery_protection = false.
Remember that this change is ONLY FOR LOCAL TESTING, in fact this line prevent Cross-Site Request Forgery attack. Changing this line will allow you to send and request data from REST without a token on each call to server side services.
FLEX PART
For the Flex part you can start with your custom GUI or, if you prefer, with an .fxp file made with Flash Catalyst acts as a code base for this tutorial. You can download directly from this link.
The interface is a list with a custom item renderer where user can see firstname, surname and company of each person in address book, in the right side you can find a white rectangle where are all person details stored in our SQLite database are displayed.
The first thing you need to do to work with Flash Catalyst file is to create a new custom component and call it MainView.mxml, then copy all MXML in default Application so you should have something like this:
<RestAndFlex:MainGroupView xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:d="http://ns.adobe.com/fxg/2008/dt"
xmlns:graphics="assets.graphics.*"
xmlns:RestAndFlex="org.mart3.insideRIA.RestAndFlex.*"
xmlns:mx="library://ns.adobe.com/flex/mx" width="400" height="300" creationComplete="init()">
<fx:Style source="Main.css"/>
<s:BitmapImage source="@Embed('/assets/images/layout/Layer 0.png')" d:userLabel="Layer 0" x="0" y="0"/>
<fx:DesignLayer d:userLabel="item">
</fx:DesignLayer>
<fx:DesignLayer d:userLabel="scrollbar">
<s:List id="people" skinClass="components.DataList1" x="14" y="153" dataProvider="{peopleList}" change="selectItem(event)" height="398"/>
</fx:DesignLayer>
<fx:DesignLayer d:userLabel="Details">
<graphics:Graphic1 x="340" y="153"/>
<fx:DesignLayer >
<s:RichText color="#BB1700" fontFamily="DIN-MediumAlternate" fontSize="17" height="21" kerning="off" lineHeight="18" text="role:" trackingRight="-0.4" d:userLabel="role: developer company: Adobe System" whiteSpaceCollapse="preserve" width="39" x="354" y="362"/>
<s:RichText color="#BB1700" fontFamily="DIN-MediumAlternate" fontSize="17" height="20" kerning="off" lineHeight="18" text="company:" trackingRight="-0.4" d:userLabel="role: developer company: Adobe System" whiteSpaceCollapse="preserve" width="78" x="351" y="391"/>
<s:TextInput skinClass="components.role_developerc_TextInput" x="393" y="363" id="roleField" focusIn="manageField(event)"/>
<s:TextInput skinClass="components.role_developerc_TextInput2" x="429" y="391" id="companyField" focusIn="manageField(event)"/>
</fx:DesignLayer>
<fx:DesignLayer>
<s:Button x="578" y="537" id="saveBtn" buttonMode="true" click="saveData()" label="SAVE" enabled="false"/>
<s:Button x="450" y="537" id="delBtn" buttonMode="true" click="deleteData(event)" label="DELETE" enabled="false"/>
</fx:DesignLayer>
<s:TextArea id="descr" skinClass="components.Loremipsumdolor_TextInput" x="353" y="219" editable="false" selectable="false" focusIn="manageField(event)" />
<s:TextInput id="nameField" skinClass="components.SurnameNameTextInput" x="352" y="191" focusIn="manageField(event)"/>
</fx:DesignLayer>
<s:BitmapImage source="@Embed('/assets/images/RasterizedItems1.png')" x="13" y="0"/>
<s:Button id="createBtn" x="224" y="567" label="CREATE NEW" click="newPerson(event)"/>
</RestAndFlex:MainGroupView>
I made a couple of changes to the original Catalyst file like the add "Create New", change "Delete" and "Save" buttons. I used the Spark theme for the interface that was set it from project preferences; however those changes are to modify the Catalyst project because currently you can create a project with Catalyst and modify with Flash Builder but you can't modify a project made with Flash Builder in Catalyst.
After defining the GUI in MXML you can start to create MainGroupView file that will interact with the MXML file by extending the Group class of Flex 4 framework and using it in the main node of the MXML file. In this class you define:
- a method to get all data from the database
- a method to delete a person from the database
- a method to modify a person's information
- a method to add a new person to the database
Before we write those methods, you must know how REST works, this table shows how to accomplish this with REST:
- GET ALL DATA → http://localhost:3000/address_books.xml (HTTP header: GET)
- RETRIEVE DATA IN PARTICULAR RECORD → http://localhost:3000/address_books/1.xml (HTTP header: GET)
- MODIFY A RECORD → http://localhost:3000/address_books/1.xml (HTTP header: PUT and pass bytearray of new data to store in database)
- DELETE A RECORD → http://localhost:3000/address_books/1.xml (HTTP header: DELETE)
- CREATE NEW RECORD → http://localhost:3000/address_books.xml (HTTP header: POST and pass an XML of new data to store in the database)
During this sample you will use the HTTPService class and as3httpclientlib library to understand how these different methods work with REST in Flex. Obviously if you work only with HTTPService class, you can't use PUT and DELETE headers, but you can solve this issue with as3httpclientlib library.
When our application starts you can populate the list component with data saved in database (if you want to populate the database use Sqlite Database Browser or populate via the Rails console that you can launch via Terminal or Prompt using ./script/console); In this sample, we will use HTTPService to request all data:
public function init():void{
service = new HTTPService();
service.addEventListener(ResultEvent.RESULT, restResult);
service.addEventListener(FaultEvent.FAULT, restFault);
service.resultFormat = "e4x";
service.method = "POST";
callRestService("address_books.xml", ALL_DATA);
}
private function callRestService(_request:String, _service:String, _data:XML = null):void{
serviceState = _service;
service.url = SERVER_URL + _request;
if(isNewPerson){
service.contentType = "application/xml";
}
service.send(_data);
}
Function callRestService is a method that you can use to request data via HTTPService, it uses the same HTTPService variable and changed only the path if it requests all data, only one record and so on.
After that you can create the update method that use as3httpclientlib:
public function saveData():void{
if(isNewPerson){
callRestService("address_books.xml", NEW_PERSON, createXMLContent());
} else {
var client:HttpClient = new HttpClient();
var uri:URI = new URI(SERVER_URL + "address_books/" + currentPerson +".xml?_method=put");
client.addEventListener(HttpRequestEvent.COMPLETE, refresh);
var ba:ByteArray = new ByteArray();
ba.writeUTFBytes(createXMLContent());
ba.position = 0;
client.put(uri,ba,"application/xml");
}
}
private function createXMLContent():XML{
var tmpXml:XML = new XML(<address_book/>);
tmpXml.appendChild(<company/>);
tmpXml.appendChild(<description/>);
tmpXml.appendChild(<firstname/>);
tmpXml.appendChild(<role/>);
tmpXml.appendChild(<surname/>);
var nameArr:Array = String(nameField.text).split(" ");
tmpXml.company = companyField.text;
tmpXml.description = descr.text;
tmpXml.firstname = nameArr[0];
tmpXml.role = roleField.text;
tmpXml.surname = nameArr[1];
return tmpXml;
}
With httpclient variable you must define the URL and make a bytearray of data that you want to send to the REST service, the createXMLContent() function retrieves all data in the Flex form and creates the XML for updating or creating a record. Also note that the HttpClient variable requests an URI variable and not a simple URLRequest, you can find this object in as3corelib library.
Finally you can add a Delete method:
public function deleteData(evt:MouseEvent):void{
var client:HttpClient = new HttpClient();
var uri:URI = new URI(SERVER_URL + "address_books/" + currentPerson + ".xml");
client.addEventListener(HttpRequestEvent.COMPLETE, refresh);
client.del(uri);
}
In this function we use del method of httpclient object to delete person instead of the put method which was used to a update record in database. Everything follows the same process:
- define the correct path for your action
- pass data if the method requires it
- listen when server replies to your request
It's the same if you use HTTPService object or HttpClient object.
You can download the final sample from this link.
FINAL CONSIDERATIONS
I think REST is a very interesting and easy way to communicate with server side technologies; I hope in the next versions of Flex or Flash that they solve the header issues and allow us to work with REST without any additional libraries. For now as3httpclientlib is the solution for this problem.
Feel free to add comment about this tutorial and I'll be happy to reply everybody.




Facebook Application Development
Nice article. One note though - Rails is not a language.
Rails is a web app framework written in Ruby. Hence "Ruby on Rails".
yes, sorry it's my mistake :P
You may want to rewrite the 3rd sentence?
With REST you can work in large web application until to small RIA, in fact is a scalable system that make all communication easier
Sorry Mitchell but I'm not agree with you.
We used REST in a RIA project and it was very useful for us to work with.
So if you have other experiences feel free to share with us
I think it's important to mention that you need a socket policy server running in order for this to work.
Greetz Erik
I mention socket in the first paragraph:
"free library called as3httpclientlib that uses a workaround using sockets to solve this Flex issue."
:D
RestfulX on github:
http://restfulx.github.com/
That library has by far the best Flex/REST/Rails integration on the planet. It uses as3httpclientlib. I'm using it on this site:
http://www.josephjewell.com/
Check it out if you haven't, it makes it so easy :).
Nice article my friend!
Nice Article...I would be interested to see how we can publish JSON through rails' RESTful services as it is mostly convenient to consume objects on the FLEX side as opposed to the XML. Every concept has its own pros and cons and REST is not an exception to that. I ve seen ppl using REST and using XML RPC style services with the claim of better performance over one another. Regardless of the comparison, it is obvious that many enterprise applications still use XML-RPC style web services and yet they serve the purpose of their existence.
hi, what you have in the tutorial for address_books_controller.rb is completely different to what you have in your solution source and both are completely different from what my generated code is.
Please fix this or advise what iis wrong.
thanks
Hi,
You´re not supposed to have span class="category1" scattered all around address_books_controller.rb, are you? :)
Cheers,
Martin
I think you missed my point. If you are running the swf within a web page. You will need a socket policy server to give you access to port 80 (or any other port) before you can use the as3httpclientlib.
I think it is something to be aware of. This will prevent people discovering this when they need to go live with their application. In development phase those restrictions aren't there.
Greetz Erik
This tutorial works with flex 3, or I need flex 4?
you need Flex 4 for this tutorial, but you can use Flex 3 too to work with RES, as3httpclientlib and so on
Rest is really a powerful protocol. It's amazing what we can do with it ! Any way good tutorial.
Nice Article...I would be interested to see how we can publish JSON through rails' RESTful services as it is mostly convenient to consume objects on the FLEX side as opposed to the XML.
devenir consultant