Accessing the Brightcove 3 Media API in Flex ActionScript 3

Written by Bob de Wit. Posted in ActionScript, Brightcove, Developer Blog, Flex

This article describes how to access the Brightcove 3 Media API using Flex 2 or 3 with ActionScript 3.It also shows how to easily use the returned data as a datasource for a grid view and deals with date conversion from and to the API. Use of Adobe Flex Builder 2 or 3 is optional.

About the Media API

The Brightcove Media Library API, or Media API for short, is a REST -based API for accessing the content and metadata in your Brightcove account. Because it is a REST-based API, it can be accessed from a wider variety of places in your web applications, not just on the client, but in your dynamically generated web pages or server-side synchronization processes, for example. REST is a standard way of accessing data stored in a remote system over HTTP. It is a cousin of SOAP and is one of the technologies that power “web services.” Its primary ability is to abstract the workings of the remote system in the transfer of its state (or information). All your code needs to understand is the format of the data that is sent back. The Media API includes read methods and write methods. The Read API consists of a set of methods which perform a variety of queries on our servers (which are cached for performance), and return sets of data in DTOs or Data Transfer Objects. For example, one API method is find_all_videos, which returns a list of VideoDTOs, where each VideoDTO contains the metadata for a specific video. Return data is formatted as JSON strings (JavaScript Object Notation). JSON is a lightweight way of transferring complex objects as strings, and nearly every language today can claim a large number of publicly available libraries to parse JSON strings into native objects. The Write API consists of a set of methods that create, update, or delete videos and playlists. For example, one Write API method is create_video, which you can use to pass in a video file, together with its associated metadata, and create a video in your Brightcove account. Note: To prevent unauthorized access to the metadata in your account, access to the API is protected with tokens that you pass as a parameter when making API calls. Like other web-based APIs, tokens are generated for you by Brightcove and protected by you. The first thing you need to do to get started is to request a token to begin development. Use this feedback form to request one from Brightcove Customer Support: https://help.brightcove.com/request-support.cfm

Creating and sending a REST Query

About the REST format Method calls using REST are basically HTTP GET requests(for read methods) or POST requests (for write methods) to a particular URL on Brightcove’s servers. The request includes the name of the method you’re calling, together with its input arguments, which are passed as parameters in the URL. The body of the HTTP response contains the results of the HTTP call as a JSON string. Method calls also require a token. Tokens are issued to accounts by Brightcove and give you access to your account using the API. There are separate tokens for read methods and write methods in the API. You append your token to the call as a URL parameter, token=<tokenString>, where tokenString is your URL-encoded token. Note: Media API tokens generally end with one or more dots (.). Be sure to include the dots when you use the API tokens – it’s easy to lose them when you cut and paste. For example, to retrieve all videos in your account, make an HTTP request that looks like: http://api.brightcove.com/services/library?command=find_all_videos&token=0Z2dtxTdJAxtbZ-d0U7Bhio2V1Rhr5Iafl5FFtDPY8E. This is a raw method call. What comes back is unprocessed and unformatted. In the examples, you’ll see ways to take the returned data and shape it in ways that are useful for an application. (Note: This call uses a demo account. To use your own account, substitute your own token.)

JSON in AS3?

There is no standard ActionScript function set for parsing JSON, so we’ll be using an open source AS3 library found on Adobe Labs called CoreLib. You can find the Library and source here: http://code.google.com/p/as3corelib Start a new Flex project called BrightcoveAPI and make sure you include a reference to the CoreLib library. The first thing we’re going to do is define your tokens and the service URI for the Media API in a code segment within the Flex Application:

Now we’ll create a Button, DataGrid and a ButtonClick handler to handle the REST API request and returned values to demonstrate the principle of a complete call.
We’ll add one of the date fields to show “conversion” from UNIX to AS3 – actually, AS3 uses the same internal notation as UNIX time codes, but the numeric value will be parsed as a string by the CoreLib JSON functions.

Making the API Call
We’ll use the same API call as the one in the raw call example before. It’s very simple to turn into AS3 code and attach it to the Button Click handler:
private function ButtonCallAPIClick(): void
	{
   	    	var request:URLRequest = new URLRequest(ServiceURL);
	       	var loader:URLLoader = new URLLoader();
	      	loader.dataFormat = URLLoaderDataFormat.TEXT;
	      	request.method = URLRequestMethod.GET;

	     	//Define the REST API variables to be passed
	     	var variables:URLVariables = new URLVariables();

	     	// First, Add your read token
	     	variables.token = ReadToken;

	     	// Add the command you want to execute
	     	variables.command = "find_all_videos";

	     	// assign the data to be sent by GET
	     	request.data = variables;

	     	// add event listener
	     	loader.addEventListener(Event.COMPLETE, handleResults);
	     	loader.load(request);
}
This is the basic template you can use for any Media API call. Simply replace the variables.command value with the command string you want to call, and add the required variables for the API function you are calling. Parsing the JSON return string We defined an event listener when the loader for the API call is complete called handleResults. In this listener, we can use the CoreLib JSON parser to convert the returned JSON string into AS3 objects:
private function handleResults(evt:Event):void
{
	//Get the returned JSON data string
	var response:String = evt.target.data as String;

	//Uncomment this if you want to see the raw response string
	//Alert.show(response);

	//The list of returned videos is embedded in the "items" property
	//of the root JSON object, so we will decode to a container
	var container:Object = (JSON.decode(response) as Object);

	//create a new ArrayCollection passing the de-serialized Array
	//ArrayCollections work better as DataProviders, as they can
	//be watched for changes.
	var dp:ArrayCollection = new ArrayCollection(container.items);

	//Convert the UNIX date into an AS3 Date
	for(var i:int = 0; i< dp.length; i++)
	{
			var video:Object = dp.getItemAt(i);
			var n:Number = video.publishedDate;
			video.publishedDate = new Date(n);
	}

	//pass the ArrayCollection to the DataGrid as its dataProvider.
	GridVideos.dataProvider = dp;
}
A little more explanation may be required here, so let’s go over this piece step by step. First, we tell Flex that the return data from the listener invoke is a string:
var response:String = evt.target.data as String;
Then we convert this string into an object using the JSON parser. If you look at the raw data output from the URI we mentioned in the REST section, you’ll see that the videos are actually embedded in a container object:
{"items":[{"creationDate":"1171267200000","economics":"FREE","id":496518762,
"lastModifiedDate":"1171324536445","length":111077,"linkText":null,"linkURL":null,
"longDescription":null,"playsTrailingWeek":2,"publishedDate":"1171324433253",
"referenceId":"title006"……
So we mimic this in AS3:
var container:Object = (JSON.decode(response) as Object);
To be able to use the list of videos directly as a Data Source for grids and lists, we need to convert it into an ArrayCollection. We can get rid of the container as well:
var dp:ArrayCollection = new ArrayCollection(container.items);
And now we can access all videos in this collection through the items property. As mentioned, AS3 uses the same internal notation as UNIX time codes, the JSON.decode() method has actually parsed these numeric values as a string. So we need to loop through these and type them as AS3 Date values:
for(var i:int = 0; i< dp.length; i++)
{
var video:Object = dp.getItemAt(i);
var n:Number = video.publishedDate;
video.publishedDate = new Date(n);
}
Finally, we can pass this Array Collection as a DataSource to the grid:
GridVideos.dataProvider = dp;

Complete Code Listing

	<!--[CDATA[
		import mx.formatters.NumberBase;

		import mx.collections.ArrayCollection;
		import mx.rpc.events.ResultEvent;
		import com.adobe.serialization.json.JSON;
		import mx.controls.Alert;

		private var ReadToken: String = "0Z2dtxTdJAxtbZ-d0U7Bhio2V1Rhr5Iafl5FFtDPY8E.";
		private var WriteToken: String = "your-write-token-here";
		private var ServiceURL: String = "http://api.brightcove.com/services/library";

		private function ButtonCallAPIClick(): void
		{
   	     	var request:URLRequest = new URLRequest(ServiceURL);
	       	var loader:URLLoader = new URLLoader();
	      	loader.dataFormat = URLLoaderDataFormat.TEXT;
	      	request.method = URLRequestMethod.GET;

	      	//Define the REST API variables to be passed
	      	var variables:URLVariables = new URLVariables();

	      	// First, Add your read token
	      	variables.token = ReadToken;

	      	// Add the command you want to execute
	      	variables.command = "find_all_videos";

	      	// assign the data to be sent by GET
	      	request.data = variables;

	      	// add event listener
	      	loader.addEventListener(Event.COMPLETE, handleResults);
	      	loader.load(request);
		}

		private function handleResults(evt:Event):void
		{
			//Get the returned JSON data string
			var response:String = evt.target.data as String;

			//Uncomment this if you want to see the raw response string
			//Alert.show(response);

			//The list of returned videos is embedded in the "items" property
			//of the root JSON object, so we will decode to a container object
			var container:Object = (JSON.decode(response) as Object);

			//create a new ArrayCollection passing the de-serialized Array
			//ArrayCollections work better as DataProviders, as they can
			//be watched for changes.
			var dp:ArrayCollection = new ArrayCollection(container.items);

			//Convert the UNIX date into an AS3 Date
			for(var i:int = 0; i

Trackback from your site.

Comments (1)

Leave a comment