Subscribe

Share

Mobile

API-First: Build APIs with Oracle Mobile Cloud Service

Integrate enterprise systems and mobile applications, using Node.js in Oracle Mobile Cloud Service.

By Chris Muir

November/December 2015

The development world is moving to an API-first paradigm, spurred by industry initiatives such as microservices, and mobile development is also leading the API charge. Oracle Mobile Cloud Service provides two types of APIs that you can externalize and consume as RESTful endpoints in your mobile applications:

  • Platform APIs are prebuilt, mobile-specific APIs that provide user services, notifications, storage, data synchronization, analytics, and other back-end services needed to support mobile apps.
  • Custom APIs are a Node.js-backed feature that enables service developers to build their own APIs for specific mobile services. There are no limits to what you can build, but a common use is creating a custom API that your mobile applications can use to retrieve and transform data from enterprise systems or from disparate cloud or web resources.

This article focuses on the last use case, integrating data from a web resource via a REST Oracle Mobile Cloud Service connector. The web resource used for the example is a test REST service at jsonplaceholder.typicode.com that models resources such as online article posts, comments, and to-do lists. Overall, it provides a nice remote set of REST endpoints to play with. In a real-world application, you’ll typically be connecting to SOAP or REST web services provisioned by your own enterprise back-end systems.

Getting Ready

To follow the steps in this article, you first must obtain an Oracle Mobile Cloud Service trial account from cloud.oracle.com/mobile. Click Try It, and then follow the prompts to create your trial account. You’ll receive a confirmation e-mail with details about how to access your Oracle Cloud account and activate your Oracle Mobile Cloud Service instance. Follow the linked documentation to complete your sign-up and activate and access Oracle Mobile Cloud Service.

ND15-MCS-f1
 

Figure 1: The Oracle Mobile Cloud Service development dashboard

Download the prebuilt files for this article, and save o65mcs-2706755.zip to a local folder on your computer. Unzip the file to a folder named OracleMagazine. This folder contains the few files you’ll need later. This article assumes that you have set up your trial account and have opened the Oracle Mobile Cloud Service portal.


Create a Mobile Back End

For each mobile application in Oracle Mobile Cloud Service, you define a mobile back end. At its simplest, the mobile back end can be thought of as the gateway through which services are exposed to mobile applications and, ultimately, mobile users.

  1. At the top left of the page, click the Options icon (the icon with three horizontal stripes, also referred to as the hamburger icon), followed by Applications -> Mobile Backends.
  2. Click New Mobile Backend.
  3. In the New Mobile Backend dialog box, enter OraMagTestBackend for Name.
  4. Click Create.
Create a Connector

An Oracle Mobile Cloud Service connector provides a declarative solution for defining the external service connections that your custom APIs can consume. As mentioned, this project uses a test REST service at http://jsonplaceholder.typicode.com. The first task is to create a REST connector that your custom API can access.

ND15-MCS-f2
 

Figure 2: The Oracle Mobile Cloud Service portal

  1. From the top left menu, select Applications -> Connectors.
  2. If this is the first time you’ve accessed the Connectors page, you’ll be presented with a page on which you can select the green REST icon.
  3. Otherwise click New Connector and then REST.
  4. In the New REST Connector API dialog box, enter the following:
    Display API Name: OraMagTestConn
    API Name: OraMagTestConn
    Remote URL: http://jsonplaceholder.typicode.com
    Short Description: Test
  5. Click Create.
  6. On the Configure REST API: OraMagTestConn page, note the connector’s internal URI, /mobile/connector/OraMagTestConn. This will be important momentarily.
  7. Click Save at the top right, and wait as Oracle Mobile Cloud Service saves your newly created connector.
  8. Having built the connector, watch this video to learn how to test it.
  9. After completing the tasks in the video, click Done if the Connector API Testing page is still open.
Create a Custom API

With the mobile back end and the connector in place, you can now build the custom API to do the grunt work. A custom API has two parts: its interface, defined as REST APIs, and its implementation through Node.js. Let’s build the interface first and expose two REST endpoints to support basic HTTP GET calls targeting the example web resources: /users and /comments.

  1. At the top left of the page, select the Options (“hamburger”) icon, followed by Applications -> APIs.
  2. Click New API.
  3. In the New API dialog box, drag the oramagtestapi.raml file from the extracted zip file on your desktop into the Upload a RAML document section at the bottom of the dialog box. Data from the RAML file populates the Display API Name, API Name, and Remote URI fields of this page. Listed between the fields you can see the API’s remote URL for invocation from a mobile client, which will look like http://<base_URL:port>/mobile/custom/OracleMagTestAPI/.
  4. In the Short Description field, enter Test.
  5. Click Create. The first time you create an API, a help page displays the option of watching a video. Watch the video if you like, and then click Got It! to continue.
  6. When the API is created from the RAML file, the RAML file appears in an editing page. At the top right of the editing page, you’ll see a small icon of a pencil over a document, with a tool tip that reads: “Enter RAML Source Editor Mode.” Click this icon to display the contents of the RAML file.

The uploaded RAML file defines the REST endpoints for the custom API. RAML is a contemporary choice for designing, defining, and documenting REST endpoints. Specifically, lines 06 to 08 define a REST endpoint, /users, that supports the HTTP GET method; lines 09 to 16 define an endpoint, /comments, that also supports the HTTP GET method but has a mandatory URI query parameter, the postId of the comment.

ND15-MCS-f3
 

Figure 3: Defining the REST endpoints in a RAML file

  1. Select the pencil icon to switch out of the RAML editor.
  2. Select the Security option near the top of the page.
  3. Turn the Allow Anonymous User Access option on.
  4. Click Save, and wait for the save complete message.

After you’ve defined the custom API’s REST endpoints, the next step is to implement internal logic through Node.js.

  1. Select the Implementations option on the left.
  2. Click JavaScript Scaffold to download the zip file containing stubs (the “scaffolding”) for each endpoint. The filename matches the API and the version number, so for this example, that’s oramagtestapi_1.0.zip.
  3. Unzip this file to your desktop, which creates a subdirectory with the same name as your API.
  4. Delete the zip file. Into the newly created subdirectory, copy the oramagtestapi.js file and the package.json file from the OracleMagazine directory, overwriting these same files in the oramagtestapi directory.
  5. Open the oramagtestapi.js file in your favorite text editor.

This is your first look at Node.js code within Oracle Mobile Cloud Service, yet JavaScript and Java developers will recognize familiar, readable syntax (see Figure 4).

ND15-MCS-f4
 

Figure 4: Examining the Node.js code that defines the API

Line 03 defines a wildcard (…/*) router to capture all requests to the generic path—in this case, calls to both endpoints (/comments and /users) defined in the RAML file for the custom API (/mobile/custom/OraMagTestAPI). The code block within the router function specifies how to handle requests.

Lines 06 and 07 reject requests that don’t match the extended URI paths of /comments or /users, returning HTTP 404s (unknown resource error code) and terminating the call on line 07.

Otherwise, assuming that the requests are for valid endpoints, line 10 calls the req.oracleMobile.rest.get function. In line 11, the first parameter to the function identifies the URI of the connector. The extended path (from line 05) is then added to this connector path. So, for example, an external query to the custom API /mobile/custom/OraMagTestAPI/users becomes a call to the connector at /mobile/connector/OraMagTestConn/users.

At runtime, Oracle Mobile Cloud Service transforms the connector URI from /mobile/connector/OraMagTestConn/users to http://jsonplaceholder.typicode.com/users.

Line 12 defines the second parameter to req.oracleMobile.rest .get, a callback function that asynchronously handles the response from the connector whenever the connector has a response from the external test REST service.

The asynchronous nature of Node.js is one of its most powerful features. Rather than waiting for responses from external I/O, the program continues running code subsequent to the function (after line 27). Only when the external service and the connector return a result does the function (defined at line 12) handle the callback. This nonblocking nature makes Node.js extremely fast, although the callback programming model requires a mind shift for programmers who are used to traditional programming languages.

Within the callback function, any error message received from the connector (on lines 13 and 14) is immediately returned to the custom API caller, and the function terminates. If there is no error and the request is to the /users path, processing will drop through to line 22 and the payload from the connector will immediately be returned, followed by a 200 HTTP status code indicating success (line 24).

However, if the request is to the /comments path, the postId parameter will be extracted from the query, by use of a JSON filter function defined on line 19, and applied on line 20 to eliminate comments from the returned JSON payload that do not match the postId.

Hypothetically, if the external REST test service provided the means to filter the data by postId via a query parameter, this logic would have been unnecessary: simply pass the postId through for the remote service to do its work. However, the sample code includes this logic to show how you can easily work with returned payloads in your Node.js code and massage the data to suit your mobile application’s needs.

At this point, you can prepare the Node.js routines for upload back to the server.

  1. Zip the oramagtestapi directory.
  2. Return to your browser.
  3. Drag and drop the new zip file onto the Upload an implementation archive link.
  4. On the API Implementation page, note the newly uploaded API and version 1.0.0, which is now the default code for this API. Click Save, and wait until the save message appears.
  5. Having completed the custom API, watch the video to learn how to test it.
Conclusion

This article introduced you to Oracle Mobile Cloud Service and demonstrated the ease of building APIs with the power of Node.js through custom APIs. Overall, Oracle Mobile Cloud Service is designed to centralize and greatly simplify the task of mobile development for enterprises; eliminate barriers to integration; and enable you to easily mobilize your enterprise, its systems, and your workforce. With such ease of use, you’re ready to lead the way in mobile, API-first development.

Next Steps

TRY Oracle Mobile Cloud Service.

READ more about Oracle Mobile Cloud Service.

WATCH Oracle Mobile Cloud Service YouTube training.

JOIN the Oracle Mobile Platform Google+ community.

 

Photography by Sergey Nivens, Shutterstock