Develop Worklight adapters with AT&T mobile APIs

Build a simple SMS application to understand Worklight's adapter framework

IBM Worklight provides an adapter framework and tools to connect mobile applications to back-end systems and web-based APIs. This article walks you through the process of developing and testing a Worklight adapter, using the Short Message Service (SMS) API provided by AT&T as an example.

Jason Hunt (djhunt@us.ibm.com), Executive Software Client Architect, IBM

Author photo - Jason HuntJason Hunt is an Executive Software Client Architect with IBM’s Sales and Distribution organization. He has 16 years of experience with enterprise software architecture and 12 years working with telecommunications companies in areas such as application high availability, cloud, and mobile. Jason’s first mobile development experience was in 1999 when he created an application to turn on the light in his home office using an X10 adapter and a Palm VII.



06 January 2013

Also available in Chinese

Introduction

While there are mobile applications that require no back-end connectivity, such as games or calculators, most enterprise mobile applications derive their benefit from mobilizing data and functions available over the network. This data and functionality may come from the enterprise’s systems or via third-party services exposed as APIs. Worklight provides an adapter framework in the Worklight server for calling these services.

Worklight supports three core adapter types:

  • HTTP for general HTTP connectivity, including RESTful and SOAP APIs
  • SQL for accessing databases
  • Cast Iron Adapter, which works with WebSphere Cast Iron to enable integration with 150-200 types of cloud and on-premise apps, such as Salesforce, SAP, and Oracle

More background on Worklight’s adapter framework is available in the "Resources" section later in this article.

In this article, I walk you through the process of developing and testing an HTTP adapter that calls a RESTful API provided by AT&T. You will learn an easy way to test back-end services, build adapters, and create mobile applications to call the adapters. With this knowledge, you’ll be able to create mobile applications that leverage the wealth of available web APIs and enterprise systems.

An exported version of the complete project covered in this article is available in the "Download" section later in this article.

AT&T APIs

AT&T provides many interesting APIs that you can integrate in a mobile application via an HTTP adapter. These APIs expose a variety of functionality from AT&T’s network and expertise, such as:

  • SMS & MMS messaging for sending and receiving messages via server-side APIs rather than on the client device.
  • Network location for locating a device using a combination of network information and, optionally, device GPS. This API works even for devices that do not have a GPS radio included.
  • Speech recognition, which, given an audio recording, provides a transcribed response using AT&T’s speech engine. The API understands several different contexts, such as business search and question-and-answer. You do not need to have a device on the AT&T network to use this API.
  • Mobile payments to allow in-app payments that are charged on an AT&T bill.

More information on AT&T’s APIs is on the AT&T Developer Program site (see the Resources section for a link).

For this article, we will use the AT&T API to send SMS messages.

Before you start

Get the free Worklight Developer Edition

Download and install the free Worklight Developer Edition.

Note: The instructions and screen shots in this article are based on the Worklight Developer Edition version 5.0.2.407-developer-edition. The instructions also work generally the same with the current version, 5.0.5.20121217-0622.

To create this application yourself, you’ll need to first complete two steps:

  1. Install the Worklight Developer Edition (see the sidebar for a link to download and install it). This article assumes you have some experience developing mobile applications with IBM Worklight.
  2. Get access to AT&T’s APIs. To send SMS messages, you need to be registered to use AT&T’s APIs. This involves two steps:
    1. Join the AT&T Developer Program, and register for API access.
    2. Register an application with AT&T. Once you have access to the AT&T APIs, you need to register your specific application. Be sure you request access to the SMS services as shown in Figure 1.
Figure 1. AT&T application registration
Screen capture of AT&T application registration

Once your application is registered, make note of two key pieces of data that you’ll need later to run your application (shown blacked out in Figure 2):

  • API key
  • Secret key
Figure 2. API key and secret key
Screen capture of a sample API key and secret key

See Resources for a link to instructions for signing up for access to AT&T's APIs.

Our sample application

The simple application we’ll create is shown in Figure 3.

Figure 3. Simple SMS application
Diagram showing the three tiers of the sample application

We’ll create a simple mobile application where the user can enter a phone number and the text message to send. When the user presses the button to send the message, this will call the sendSMS procedure inside the ATTAPIAdapter running on the Worklight server.

AT&T’s API calls require a client credentials token, which we’ll obtain using a second procedure in our adapter, getClientCredentials. This procedure will call the AT&T Client Credentials API to obtain the access token. Then the sendSMS procedure can call the AT&T Send SMS API to send the text message.

To develop this application, we’ll work from right-to-left in Figure 3 and follow three major steps:

  • Test the AT&T services
  • Develop the adapter
  • Develop the mobile application

The benefit of this approach is that it allows you to achieve early success with your implementation without completing the entire application. Also, multiple developers working on one application could work concurrently on various steps, as long as you define your interfaces ahead of time.


Test the AT&T services

Before trying to code the adapter, I find it helpful to ensure that you understand how your back-end service works. We’ll use the built-in testing framework within Worklight to help us test the back-end service.

First, we need to create a Worklight project, application, and adapter. Launch the Worklight development environment and choose File > New > Worklight Project (may be under “Other”). Name your project ATTAPI and click Next (see Figure 4).

Figure 4. Create a Worklight project
Screen capture to create a new Worklight project

On the next screen, enter an Application name of SimpleSMS. Select the option to Add Dojo Toolkit and click Finish (see Figure 5).

Figure 5. Create a Worklight application
Screen capture to create a new Worklight application

Once your project and application are created, we can create the adapter. Right-click on your project name (“ATTAPI”) and select New > Worklight Adapter. Select an Adapter Type of HTTP Adapter. Name your adapter ATTAdapter and click Finish (see Figure 6).

Figure 6. Create a Worklight adapter
Screen capture to create a new Worklight adapter

When the Adapter Editor comes up, we’ll need to configure it to access AT&T’s APIs. Open the twistie next to Connectivity, select Connectivity Policy, and update the following fields:

  • Protocol: https
  • Domain: api.att.com
  • Port: 443

Next, you’ll want to rename the two existing procedures (getStories and getStoriesFiltered) with the names getClientCredentials and sendSMS instead. See Figure 7.

Figure 7. Editing the adapter configuration
Screen capture of the Adapter Editor

Press Ctrl-s to save the adapter configuration. The source of your ATTAdapter.xml should look something like Listing 1.

Listing 1. ATTAdapter.xml
<?xml version="1.0" encoding="UTF-8"?>

<wl:adapter name="ATTAdapter"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:wl="http://www.worklight.com/integration"
	xmlns:http="http://www.worklight.com/integration/http">

	<displayName>ATTAdapter</displayName>
	<description>ATTAdapter</description>
	<connectivity>
		<connectionPolicy xsi:type="http:HTTPConnectionPolicyType">
			<protocol>https</protocol>
			<domain>api.att.com</domain>
			<port>443</port>			
		</connectionPolicy>
		<loadConstraints maxConcurrentConnectionsPerNode="2" />
	</connectivity>

	<procedure name="getClientCredentials"/>

	<procedure name="sendSMS"/>
	
</wl:adapter>

We’ll also need to clean up your adapter implementation ATTAdapter-impl.js. Open the file and replace all of the code with the code in Listing 2:

Listing 2. Initial ATTAdapter-impl.js
function getClientCredentials() {

}

function sendSMS() {
	
}

Save the file by pressing Ctrl-s. These are just placeholder functions until we’ve tested the back-end service and can complete the implementation of the adapter.

Testing the Credentials Service

AT&T’s APIs, like many third-party APIs, require that you authenticate your application before calling any APIs. AT&T uses the OAuth 2.0 client credentials flow to accomplish this. This authorization method works for all of the AT&T APIs except those where you need to get the AT&T subscriber’s consent before using the API (such as the location and device capabilities APIs).

To use the client credentials flow, we will pass in our application’s credentials and receive an access token to use on subsequent API calls. Right-click on the ATTAdapter in the Project Explorer and choose Run As > Invoke Worklight Back-end Service (see Figure 8).

Figure 8. Invoke Worklight Back-end Service
Screen capture of invoking Worklight Back-end Service

This will present a screen where you can construct the JSON object used by Worklight’s invokeHTTP method. Replace the code with the code from Listing 3.

Listing 3. Input to test credentials service
{
	    'method' : 'post',
	    'path' : 'oauth/access_token',
	    'parameters' : {
		    'grant_type' : 'client_credentials',
		    'client_id' : 'YOUR API KEY GOES HERE',
		    'client_secret' : 'YOUR SECRET KEY GOES HERE',
		    'scope' : 'SMS'
		}
}

In the indicated locations, substitute the API key and secret key that you received from AT&T when you registered your application.

You can see from the code that we’re submitting an HTTP POST call to the URL path 'oauth/access_token'. The parameters indicate that we’re using the client credentials grant type in OAuth 2.0. Finally, the scope parameter says which AT&T APIs we want to use in subsequent calls. We’re only specifying SMS for this application. See Figure 9.

Figure 9. Editing call to credential service
Screen capture of Edit Configuration

Click Run. If the call was successful, you should see a response like Figure 10.

Figure 10. Result from calling credentials service
Screen capture of Edit Configuration

Important fields to look at in the response are the statusCode and statusReason, which tell you the HTTP response codes. Then you can look at the contents of the response. In this case, we’re interested in the access_token response parameter, which will be needed when we call the SMS API. Copy and save the access_token from your response to use in the next step.

Testing the SMS Service

Now that you’ve authenticated your application to AT&T, we can send a test SMS message directly to AT&T. We’ll follow a similar approach to the previous step. Right-click the ATTAdapter in the Project Explorer and choose Run As > Invoke Worklight Back-end Service. This time, use the code from Listing 4 to call your back-end service:

Listing 4. Inputs to SMS service
{
	    'method' : 'post',
	    'path' : 'rest/sms/2/messaging/outbox',
	    'headers' : {
		    'Authorization' : 'Bearer YOUR-ACCESS-TOKEN-HERE',
	    },
	    'parameters' : {
		    'Address' : 'tel:YOUR-ATT-PHONE-NUMBER-HERE',
		    'Message' : 'My SMS message'
	    }
}

Replace YOUR-ACCESS-TOKEN-HERE with the access token you received from the last step, and replace YOUR-ATT-PHONE-NUMBER-HERE with a phone number of an AT&T subscriber to receive the text message, in the format 3145551212. See Figure 11.

Figure 11. Editing call to SMS service
Screen capture of Edit Configuration for editing call to SML service

Click Run. If the call was successful, you should see a response like Figure 12.

Figure 12. Result from calling SMS Service
Screen capture of Edit Configuration for editing call to SML service

Note that the statusCode for this response is 201, meaning that the SMS message was created, but not necessarily delivered. AT&T offers additional APIs to check if and when the SMS message was actually delivered.

Of course, you should also have received a text message at the phone number you entered. The text message will have a return address of the shortcode that AT&T provisioned for you when you created your application. See Figure 13.

Figure 13. An SMS message sent via Worklight
Screen capture of an SMS message sent via Worklight

Develop the adapter

The good thing about using the “Invoke Worklight back-end service” testing framework is that it gets you most of the way to writing your adapter. All you need to do is take the code from the back-end service testing and wrap it into a JavaScript function.

Let’s start with the getClientCredentials procedure.

Developing the getClientCredentials procedure

To develop our adapter code, we need to edit the ATTAdapter-impl.js with our implementation. Listing 5 shows what the getClientCredentials implementation should look like. Place this code into ATTAdapter-impl.js.

Listing 5. getClientCredentials() procedure
function getClientCredentials() {

	var apikey = WL.Server.configuration["att.apikey"];
	var secret = WL.Server.configuration["att.secret"];
	var input = {
	    'method' : 'post',
	    'path' : 'oauth/access_token',
	    'parameters' : {
		    'grant_type' : 'client_credentials',
		    'client_id' : apikey,
		    'client_secret' : secret,
		    'scope' : 'SMS'
	    }	
	};
	
	return WL.Server.invokeHttp(input);
}

This is very similar to the code that we used to test the back-end service. The primary changes we needed to make were to:

  • Wrap all the JSON input into a variable
  • Use that variable to call WL.Server.invokeHttp

You’ll also notice that we are obtaining the API key and secret key from the Worklight server configuration file instead of hardcoding them in the adapter code. For this to work, you’ll need to open the worklight.properties file under server/conf and add the two lines in Listing 6.

Listing 6. Additions to worklight.properties
att.apikey=YOUR-API-KEY-GOES-HERE
att.secret=YOUR-SECRET-KEY-GOES-HERE

Of course, substitute your API and secret keys in the appropriate spots.

Testing the getClientCredentials procedure

Before implementing the sendSMS method, let’s be sure our new getClientCredentials procedure works.

Right-click ATTAdapter in the Project Explorer and choose Run As > Invoke Worklight Procedure. See Figure 14.

Figure 14. Invoking a Worklight procedure
Screen capture of an SMS message sent via Worklight

For Procedure name: select getClientCredentials. This adapter has no parameters, so just click Run. See Figure 15.

Figure 15. Editing call to getClientCredentials procedure
Screen capture of Editing call to getClientCredentials procedure

If successful, you should see a response similar to what you received when you invoked the AT&T credentials API earlier.

To more easily consume the response from this procedure, let’s create a helper function that will extract the access_token and provide it to any code that calls this helper function.

Edit the ATTAdapter-impl.js and add the function in Listing 7:

Listing 7. getToken() helper function
function getToken() {
	var token;
	var input = {
			'adapter' : 'ATTAdapter',
			'procedure' : 'getClientCredentials',
			'parameters' : [],
			};
	var output = WL.Server.invokeProcedure(input);
	if(output.isSuccessful){
		WL.Logger.debug("call to getAuthCode successful");
		token = output.access_token;
		WL.Logger.debug("Token is " + token);
		}
	else {
		WL.Logger.debug("call to getAuthCode not successful");
		return;
	}
	return token;
}

In this function, we first call the getClientCredentials procedure using the WL.Server.invokeProcedure method. Then if the call was successful, we extract the token from the output using output.access_token and return that value to the calling code. We also use WL.Logger.debug to output helpful debug messages into the console.

We’ll use this helper function in the next section.

Developing the sendSMS procedure

Much like we did for getClientCredentials, we can build our sendSMS procedure using the code from testing the back-end service.

Edit the ATTAdapter-impl.js and modify the sendSMS function as shown in Listing 8:

Listing 8. sendSMS() procedure
function sendSMS(telnum, text) {
	
	var token = getToken();  
	var input = {
	    'method' : 'post',
	    'path' : 'rest/sms/2/messaging/outbox',
	    'headers' : {
		    'Authorization' : 'Bearer ' + token,
	    },
	    'parameters' : {
		    'Address' : 'tel:' + telnum,
		    'Message' : text,
	    },
	};
	
	return WL.Server.invokeHttp(input);
}

Again, we took the input JSON object from testing, and assigned it to a variable before calling WL.Server.invokeHttp. You’ll also notice that we obtain the token by calling our helper function getToken(). Finally, we pass in the phone number and message text as parameters to the procedure.

Testing the sendSMS procedure

Now let’s be sure all of our procedures work.

Right-click the ATTAdapter in the Project Explorer and choose Run As > Invoke Worklight Procedure. For Procedure name: select sendSMS. Then enter the AT&T phone number and message text in the Parameters box, like this:

'3145551212','This is my message text'

Click Run. See Figure 16.

Figure 16. Editing call to sendSMS procedure
Screen capture of Editing call to getClientCredentials procedure

If successful, you should see a response similar to what you received when you invoked the AT&T SMS API earlier, and you should receive a text message on your phone.

Congratulations, you now have a fully functional adapter to call AT&T’s SMS API!


Develop the mobile application

To complete our application, we’ll create a simple mobile application that will call the sendSMS procedure.

Under apps/SimpleSMS/common, open the SimpleSMS.html file and replace with the code in Listing 9.

Listing 9. SimpleSMS.html
	<!DOCTYPE html>		

<html>

	<head>

		<meta charset="utf-8" />

<meta name="viewport"

      content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />

<title>SimpleSMS</title>

		<link rel="shortcut icon" href="images/favicon.png" />

		<link rel="apple-touch-icon" href="images/apple-touch-icon.png" />

		<link rel="stylesheet" href="css/reset.css" />

		<link rel="stylesheet" href="css/SimpleSMS.css" />

<script type="text/javascript"

	data-dojo-config="isDebug: false, async: true, parseOnLoad: true"

	src="dojo/dojo.js"></script>

<script type="text/javascript" src="dojo/core-web-layer.js"></script>

<script type="text/javascript" src="dojo/mobile-ui-layer.js"></script>

<script type="text/javascript" src="dojo/mobile-compat-layer.js"></script>

<script type="text/javascript">
require(
// Set of module identifiers
[ "dojo", "dojox/mobile/parser", "dojox/mobile/Heading", "dojox/mobile", 
"dojox/mobile/compat", "dojox/mobile/deviceTheme", "dojox/mobile/Button", 
"dojox/mobile/TextBox", "dojox/mobile/TextArea" ],
// Callback function, invoked on dependencies evaluation results
function(dojo) {
	dojo.ready(function() {

	});
});
</script>

<meta name="apple-mobile-web-app-capable" content="yes">

</head>

	<body onload="WL.Client.init({})" id="content" style="display: none">

	<h1 data-dojo-type="dojox.mobile.Heading"

		data-dojo-props="label:'SimpleSMS'"></h1>

	Telephone #:

	<input data-dojo-type="dojox.mobile.TextBox" value="3145551212" id="telnum">

	<br>

	Text Message:

	<textarea data-dojo-type="dojox.mobile.TextArea" 
id="text">Hello from Worklight</textarea>

	<br><button data-dojo-type="dojox.mobile.Button" 
onclick="submitSMS()">Submit SMS</button>

	<ul id="itemsList"></ul>

		<!-- application UI goes here -->



		<script src="js/SimpleSMS.js"></script>

		<script src="js/messages.js"></script>

		<script src="js/auth.js"></script>

	</body>

</html>

Error in HTML editor?

If you see the error message “Response cannot be parsed, please contact support” in the design portion of your HTML editor, this is a known issue. You can fix it by:

  • Creating a Worklight environment, such as iPhone or Android. Right-click “SimpleSMS” in the project explorer, choose New > Worklight Environment, and complete the form.
  • After the environment is created, choose that environment as the “skin” in the upper right corner of your HTML design editor.

Note a couple of items in this relatively simple page:

  • The input field for the telephone number and text message are given IDs of telnum and text, respectively.
  • When the SendSMS button is clicked, we’ll call the JavaScript function submitSMS()

Now, let’s implement the client-side JavaScript to call the adapter. Open apps/SimpleSMS/common/js/SimpleSMS.js and add the code in Listing 10 to the beginning of the file:

Listing 10. Variable declaration in SimpleSMS.js
      var busyIndicator = null;


This will be the variable to display the busy indicator while we’re calling the back end.

Then, insert the code in the wlCommonInit()function to initialize the busy indicator. See Listing 11.

Listing 11. wlCommonInit() in SimpleSMS.js
function wlCommonInit(){
	// Common initialization code goes here
	busyIndicator = new WL.BusyIndicator('AppBody');
}

Now you can add the function to invoke the sendSMS procedure. See Listing 12.

Listing 12. submitSMS() function in SimpleSMS.js
function submitSMS(){
	busyIndicator.show();
	var telnum = $('#telnum').val();
	var text = $('#text').val();
	var invocationData = {
			adapter : 'ATTAdapter',
			procedure : 'sendSMS',
			parameters : [telnum,text]
		};
	
	WL.Client.invokeProcedure(invocationData,{
		onSuccess : submitSMSSuccess,
		onFailure : submitSMSFailure,
	});
}

This method pulls the values for the telephone number and text message from the mobile page and invokes the sendSMS procedure for the ATTAdapter.

Next, we need to implement the callback functions for success or failure of the procedure call. Place these in the same SimpleSMS.js file. See Listing 13.

Listing 13. Callback functions for procedure call success or failure
function submitSMSSuccess(result){
	WL.Logger.debug("Submit SMS success");
	busyIndicator.hide();

	WL.Logger.debug("status code: " + result.invocationResult.statusCode);
	if (result.invocationResult.statusCode == '201') 
		WL.SimpleDialog.show("SMS", "Message sent",
				[{
					text : 'OK' 
				}]);
	else 
		submitSMSFailure(result);
}

function submitSMSFailure(result){
	WL.Logger.error("Submit SMS failure");
	busyIndicator.hide();
	WL.SimpleDialog.show("SMS", "Unable to successfully submit SMS message", 
	[{
		text : 'Reload App',
		handler : WL.Client.reloadApp 
	}]);
}

For both of these functions, we’re using the WL.SimpleDialog.show method to display the results for the user. Note that even if the procedure was successfully invoked, AT&T might have returned an error code. That’s why in the submitSMSSuccess function we check to see if the returned statusCode equals 201 before displaying a successful message.

Testing the application

Now we can test the application end-to-end. First, deploy the adapter by right-clicking the ATTAdapter folder and choosing Run As > Deploy Worklight Adapter. See Figure 17.

Figure 17. Deploying the adapter
Screen capture of deploying the adapter

Now, deploy the application by right-clicking the SimpleSMS folder under apps and select Run As > Build All and Deploy. See Figure 18.

Figure 18. Building and deploying the mobile application
Screen capture of building and deploying the mobile application

Wait until you receive the message in the console:

Application 'SimpleSMS' deployed successfully with all environments

You can then open the Worklight console, usually at the URL
http://127.0.0.1:8080/console/

For the simplest testing, just click Preview as Common Resources. See Figure 19.

Figure 19. The Worklight Console Enlarge the figure
Screen capture of the Worklight Console

When the application comes up, enter an AT&T telephone number and text message and click SendSMS. See Figure 20.

Figure 20. Testing the mobile application
Screen capture of testing the mobile application

You should receive the SMS message on your phone and see a pop-up message stating that the message was sent (Figure 21).

Figure 21. Success dialog message
Dialog box showing Message sent

You can do additional testing by creating additional Worklight environments and testing using the Mobile Browser Simulator or device emulators, or on actual devices.


Conclusion

Improvements to the application

This application was made simple for learning purposes. You should make a couple of improvements before using it in any production environment:

  • Cache the access token for reuse over subsequent API calls to minimize the number of back-end calls.
  • Add error handling for situations where the access token cannot be obtained.

In this article you saw a cumulative way to build adapters that lets you gain success early:

  • Testing the back-end API directly using Run As > Invoke Worklight Back-end Service
  • Developing the adapter and testing it using Run As > Invoke Worklight Procedure
  • Developing the front-end mobile application and testing it in the Worklight console

You also saw how APIs provided by AT&T can add capabilities to mobile applications. To investigate AT&T’s APIs further, see the Resources below for more information.


Download

DescriptionNameSize
Complete project for this articleATTAPISendSMSproject.zip11MB

Resources

Learn

Get products and technologies

  • Worklight Developer Edition: Download and install IBM's mobile development and server platform for smartphone and tablet apps.
  • Worklight adapters from AT&T: Download the set of adapters that AT&T has created for the following APIs: Speech, SMS, Device Capabilities, Notary Management, OAuth, and Payment.
  • AT&T API catalog: See a complete listing of AT&T APIs.

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into Mobile development on developerWorks


  • Bluemix Developers Community

    Get samples, articles, product docs, and community resources to help build, deploy, and manage your cloud apps.

  • Mobile weekly

    Innovations in tools and technologies for mobile development.

  • DevOps Services

    Software development in the cloud. Register today to create a project.

  • IBM evaluation software

    Evaluate IBM software and solutions, and transform challenges into opportunities.

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Mobile development
ArticleID=854137
ArticleTitle=Develop Worklight adapters with AT&T mobile APIs
publish-date=01062013