Oracle Mobile Cloud Service

Custom APIs and Custom Code

diagram of custom API within MCS architecture

You can create custom REST APIs to build up a library of services that can be used by your mobile apps. Custom APIs are particularly useful for aggregating data from other sources, adding any relevant business logic, and returning results in a mobile-friendly way.

described in surrounding text

Note: Before you start, complete the Get Started with Mobile Development tutorial that is offered within Oracle Mobile Cloud Service on its Home page. That tutorial provides the mobile backend that you will use here.

part 1Create a custom API and define its endpoints

In creating a REST API, you define a set of endpoints that can be called by an application. These endpoints consist of resources, REST methods to act on those resources, and request and response details. Let's take a look at how we might create an API with an incidents resource, a GET method to retrieve those resources, and a POST method to add a new object to incidents.

First let's create the API.

  1. Click menu icon in the upper left corner of the page and select Applications > APIs.
  2. Click New API.
  3. In the New API dialog, fill in the following fields:
    • API Display Name: Incident Report
    • API Name: incidentreport
    • Short Description: Custom API for Getting Started tutorial
  4. Click Create.

Now let's create a resource.

  1. In the Designer, click Endpoints.
  2. Click New Resource.
  3. Fill in the fields as follows:
    • Resource Path: incidents
    • Display Name: Incidents
    • Resource Description: All incident reports.

And for the resource, we need to add methods in order to create endpoints. First we'll create a GET to retrieve all incident reports.

  1. Click Methods.
  2. Click Add Method and select GET.
  3. Click Add Parameter.
  4. Fill in the fields as follows:
    • Query: Query
    • Parameter: technician
    • Display Name: Technician ID
    • String: String
  5. Click Add Parameter.
  6. For the second parameter, fill in the fields as follows:
    • Query: Query
    • Parameter: location
    • Display Name: Location
    • String: String
  7. For the location parameter, click Click to add a parameter description.
  8. Insert the following description into the text area:
    location of contact or technician
  9. For the location parameter, click Click to add an example.
  10. Insert the following description into the text area:
    39.355589 -120.652492
  11. Click Responses.
  12. Click Add Response.
  13. Leave the response as 200 - OK.
  14. Click Add Media Type.
  15. Leave the Media Type as application/json.
  16. In the Example text area, paste the following code:
    {
      "items":
    	 [
    	   {
    		 "id": 100,
    		 "title": "Leaking Water Heater",
    		 "createdon": "2014-07-18 17:21:55 PST",
    		 "contact": {
    			 "name": "Lynn Adams",
    			 "street": "45 O'Connor Street",
    			 "city": "Ottawa",
    			 "postalcode": "a1a1a1",
    			"username": "johnbeta"
    		 },
    		 "status" : "New",
    		 "priority" : "High",
    		 "driveTime" : 30,
    		 "imageLink": "storage/collections/2e029813-d1a9-4957-a69a-fbd0d7431d77/objects/6cdaa3a8-097e-49f7-9bd2-88966c45668f?user=lynn1014"
    	   },
    	  {
    		 "id": 101,
    		 "title": "Smoking Oven",
    		 "createdon": "2014-07-18 17:21:55 PST",
    		 "contact": {
    			 "name": "Lynn Adams",
    			 "street": "45 O'Connor Street",
    			 "city": "Ottawa",
    			 "postalcode": "a1a1a1",
    			 "username": "johnbeta"
    		 },
    		 "status" : "In Progress",
    		 "priority" : "Medium",
    		 "driveTime" : 10,
    		 "imageLink": "storage/collections/2e029813-d1a9-4957-a69a-fbd0d7431d77/objects/6cdaa3a8-097e-49f7-9bd2-88966c45668f?user=lynn1014"
    	   }
    	 ],
       "uris":
    	 [
    		"/mobile/custom/incidentreport/incidents/100",
    		 "/mobile/custom/incidentreport/incidents/101"
    	  ],
    	"etags":
    	  [
    		  "100",
    		  "101"
    	  ]
    }
    
  17. Scroll upward and click Add Response again.
  18. Scroll back down, and for the new response select 404 - Not Found.
  19. Scroll back to the top click Save.

Now we'll create a POST to add a new incident to the collection.

  1. Click Add Method and select POST.
  2. For the POST method, click Add Media Type.
  3. Select application/json.
  4. In the Example text area, paste the following:
    { 
      "id": 100, 
      "title": "Leaking Water Heater", 
      "createdon": "2014-07-18 17:21:55 PST", 
      "contact": [ { "email": "lynn.smith@a.com", "name": "Lynn Smith", "street": "555 America Way", "city": "Austin", "postalcode" : "78731" } ],
      "status" : "New",
      "priority" : "High",
      "driveTime" : 30,
      "imageLink": "/mobile/platform/storage/1.0/collections/Foo/objects/FD37E8D4A7152B4EE0435D329C0AFFD0?type=guid" 
    }
  5. For the POST method, click Responses and then Add Response.
  6. Select 201 - Created.
  7. Click Add Media Type and select application/json.
  8. Scroll back up and click Save.

part 2 Associate the API with a mobile backend

Before you can deploy an API, it has to be associated with a mobile backend. The mobile backend provides the security context for accessing the API, including the users that have permissions.

  1. In the menu on the left, click Mobile Backends. (If you have hidden the menu, click menu icon in the upper left corner of the page and select Applications > Mobile Backends.)
  2. Select the incidentreports backend and click Open.
  3. In the left navigation area for the incidentreportsmobile backend, click APIs.
  4. Click Select APIs.
  5. For the Incident Report API, click the Select API icon icon.

part 3Test the endpoints with mock data

To make sure that the API generally works as expected, let's test it with some mock data.

As part of this task, we'll also set up the default API designer test credentials. You need to provide credentials whenever you test an API. By setting up default test credentials, you avoid having to enter credentials each time you test an API.

  1. Navigate back to the API designer by clicking Applications > APIs in the main menu. (If you have hidden the menu, click menu icon in the upper left corner of the page and then select Applications > APIs.)
  2. Select the Incident Report API and click Test.
  3. Click Default API Designer Test Credentials.
  4. In the dialog, if you haven't already done so at some other point, select the mobile backend to use and its version, select OAuth Consumer as the authentication method, and fill in the user name and password for your test user. You can use the same test user that you used in the Get Started with Mobile Development tutorial on the Mobile Cloud Service home page.
  5. For the GET /incidents endpoint, click Test Endpoint.

    In the Response Status section, you should see a 200 code and the example data you entered when defining the API.

  6. For the POST /incidents endpoint, click Test Console and then click Use Example.
  7. Click Test Endpoint.

    In the Response Status section, you should see a 201 code and the example data you entered when defining the API.


part 4Implement the API

Now that you have the API defined, it's time to implement the API with JavaScript code. You can get started by downloading a scaffold that provides stubs for the functions that you need to implement for each endpoint, as well as some sample code.

  1. Navigate back to the API designer by clicking Applications > APIs in the main menu. (If you have hidden the menu, click menu icon in the upper left corner of the page and then select Applications > APIs.)
  2. Select the Incident Report API and click Open.
  3. Click Implementations.
  4. Click JavaScript Scaffold to download the scaffold.
  5. On your system, unzip the scaffold file.
  6. Open incidentreports.js and replace the contents with the following code:
    module.exports = function(service) {
    
      service.post('/mobile/custom/incidentreport/incidents', function(req,res) {
        console.log('getting ready to call POST /mobile/custom/incidentreport/incidents');
        var newInstance = {};
        newInstance = req.body;
        return res.send(201, newInstance);
      });
    
      service.get('/mobile/custom/incidentreport/incidents', function(req,res) {
        console.log('getting ready to call GET /mobile/custom/incidentreport/incidents');
        var result = {};
        res.send(200, result);
      });
    
    };
    
  7. Open the package.json file to view the contents of the manifest for your custom code implementation. In this file you include the version of the implementation as well as any information about dependencies or libraries that you are including.
  8. (Optional) In the package.json file, change the version number for the implementation.

    If somebody else on your team has already done this tutorial and uploaded an implementation with a version number of 1.0, you may wish to change the version number so that you don't overwrite the other implementation.

  9. Run npm install within the directory containing the package.json file. (Strictly speaking, this step isn't necessary for this simple example, but you will need to do this whenever you have added dependencies or extra libraries to your implementation.)
  10. Create a zip file of these artifacts, including the root folder containing the package.json file.

    You can name the zip anything you want.

  11. In the API designer, open the incidentreport API.
  12. In the left navigation bar, click Implementations.
  13. At the bottom of the API Implementation page, click the Upload an implementation archive link and navigate to the implementation zip on your system.

The system will do a quick check to make sure that the basics of the implementation, such as the contents of such as the package.json, are in order. If they are, you will get confirmation that the file has been uploaded and validated.


part 5Test the implementation

Now that you have uploaded an implementation, you can test the API against that implementation.

  1. On the Implementations page, click Test.
  2. In the Endpoints page, navigate to GET/incidents and click Test Endpoint.

    You should see the static data that you entered in the implementation returned.

  3. In the Endpoints page, navigate to POST/incidents, click Test Console and then click Use Example.
  4. Click Test Endpoint.

    You should see the static data that you entered in the implementation returned.

Now let's take a look at how all of this is logged.

  1. In the menu on the left, click Mobile Backends. (If you have hidden the menu, click menu icon in the upper left corner of the page and select Applications > Mobile Backends.)
  2. Double-click your mobile backend.
  3. Click Diagnostics.
  4. Click Logs.
  5. Double-click individual entries to view detail.

    You will see both messages logged by the system automatically and those that result from console messages that you inserted in the custom code.

Note: When you upload an implementation, that implementation becomes the default that you test against. If you would like to switch implementations (or go back to testing with example data), go the Implementations page, select the implementation you'd like to test against (or Mock for testing against examples provided in the API definition), and click Set as Default.


part 6Next steps