Using IBM Worklight HTTP Adapters with REST/JSON Services
Abstract The IBM Worklight Server provides 'adapters' which can issue requests to web services, databases, and other applications on behalf of mobile device applications. Adapters can be used to combine information from multiple sources into single responses to mobile devices. They can also modify data before the request and after the response using server-side javascript, and can even be used to cache freq This introductory tutorial explains how to create and use an HTTP Adapter and mobile application to fetch data from a web service which returns data in JSON format. Introduction I recently started using IBM Worklight to build mobile apps. I needed to write an app which fetches information from a REST service, where the data is returned in JSON format. I chose to use a server-side HTTP adapter to issue the request, in anticipation of future requirements to fetch additional data from other sources. To figure out the secrets, I wrote an HTTP adapter which submits an address to the Google Geocoding Service. This public service returns the latitude and longitude coordinate values (along with a lot of other information) for the address specified in the request. After the adapter was working on the server, I enhanced my HelloWorklight mobile app to request coordinates for several address locations from the HTTP adapter. Figure 1 shows a high-level view of the
traffic flow. (a) The mobile app issues a request to the HTTP
Adapter which runs in the Worklight Server. (b) The adapter sends the
web request to the backend web service. (c) The web service returns a
response in JSON format to the adapter. (d) Finally, the adapter
returns the response in JSON format to the mobile app. ![]() References The IBM Worklight website has a lot of good tutorials. I learned everything I needed for this exercise from several tutorials in the section named 'Server-Side Development': http The Google Geocoding Service is simple to use. Requests are of the form: http Responses contain a large JSON structure which includes latitude and longitude values. Complete documentation is here: http Prereqs I first set up IBM Worklight in Eclipse on my laptop, created the HelloWorklight project according to the initial tutorials, and installed the resulting APK on my Android mobile phone. I followed the tutorials in the first two sections here http Step 1 of 4. Create a basic HTTP adapter to fetch JSON data from a web service Start Eclipse. Right-click Hell Project name: Hell Adapter type: HTTP Adapter Adapter name: myRESTAdapter This created several subdirectories and files. I expanded and edited file Hell I changed the 'domain' statement to point to the Google Geocoding Service site: <dom I listed one procedure. The term 'procedure' refers to a javascript method in myRE <procedure name I expanded and edited file Hell I deleted everything in the file and I wrote one small new function. The function creates an object named 'input' and calls the Worklight Server method invokeHttp(). The path variable was set to point to the Google Geocoding Service: maps In this initial coding, the method returned the entire large JSON response object, as received from the Google Geocoding Service. function getG var input = { method : 'get', returnedContentType : 'json', path : 'map parameters : { 'address' : pAddress, 'sensor' : 'false' // hard-coded } }; return WL.S } That's it. Coding of the initial HTTP Adapter is now complete. It's time to test. Step 2 of 4. Test the HTTP adapter within Eclipse IBM Worklight provides a neat ability to test the javascript functions in adapter directly from Eclipse. Input parameters can be specified manually, simulating values which will eventually be provided by a mobile app. This lets us debug the adapter in a small environment. I tested the adapter by expanding Hell ![]() I selected my project, adapter, and javascript method, I typed a physical address (between quotes) in the parameter box, then clicked 'Run'. ![]() After a little debugging, I finally got a successful response. The Worklight 'Invoke Procedure Result' window shows the entire JSON structure returned by the Google API. It can be scrolled up and down to see more values, including the latitude and longitude I wanted. ![]() Success. This proved that I could issue a request to the web service and get a usable response. Step 3 of 4. Modify the response data using server-side javascript within the HTTP Adapter My next step was to extract the latitude and longitude values from the JSON response structure. The JSON response is huge, and I did not want to send it all to my mobile app. Aside: For trendy buzzword aficiandos, processing at this point in the overall flow is called 'server-side javascript' processing... I added some additional javascript in myRE // Extract latitude and longitude from the response. var type = typeof response if ("object" == type) { if (true == resp // Drill down into the response object. var results = resp var result = results[0]; var geometry = result["geometry"]; var location = geom // Return JSON object with lat and lng. return location; } else { // Returning null. Web request was not successful. return null; } } else { // Returning null. Response is not an object. return null; } Repeating the test again showed that the code now returned only the latitude and longitude values, along with a boolean 'isSuccessful'. ![]() The HTTP adapter running on the Worklight server is now ready to be used by a mobile app. Step 4 of 4. Enhance the HelloWorklight mobile app to fetch the JSON data from the HTTP adapter I added new functionality to the HelloWorklight mobile app which I had developed previously. I put everything in the HTML file for convenience. Here is the code: In the body section, I added HTML for several buttons. They list addresses in cities around the world. The buttons all call one javascript method mobGmapLatLng() in the mobile app. Hello Worklight with getGmapLatLng <p> <button oncl <p> <button oncl <p> <button oncl <p> <button oncl <p> <button oncl In the head section, I added a new javascript function mobGmapLatLng. This method invokes the Worklight Client API function 'invokeProcedure()' on the mobile device. This function calls into the Worklight Server, and connects the request to my javascript method getGmapLatLng() in the HTTP Adapter. I specified the name of the adapter, name of the function (aka procedure), and the address parameter in object 'invocationData': function mobG var invocationData = { adapter : 'myRESTAdapter', procedure : 'getGmapLatLng', parameters : [ pAddress ] }; WL. onSuccess : mobG onFailure : mobG }); } I also added two methods, one to handle a successful response, the other to handle a failed response. The success handler parses the JSON response object from the HTTP adapter, and displays it to the user in an alert. function mobG var httpStatusCode = result.status; if (200 == httpStatusCode) { |