Custom APIs and Custom Code
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.
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.
Create 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.
- Click and select Applications > APIs.
- Click New API.
- 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
- API Display Name:
- Click Create.
Now let's create a resource.
- In the Designer, click Endpoints.
- Click New Resource.
- Fill in the fields as follows:
- Resource Path:
incidents
- Display Name: Incidents
- Resource Description:
All incident reports.
- Resource Path:
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.
- Click Methods.
- Click Add Method and select GET.
- Click Add Parameter.
- Fill in the fields as follows:
- Query:
Query
- Parameter: technician
- Display Name:
Technician ID
- String:
String
- Query:
- Click Add Parameter.
- For the second parameter, fill in the fields as follows:
- Query:
Query
- Parameter: location
- Display Name:
Location
- String:
String
- Query:
- For the
location
parameter, click Click to add a parameter description. - Insert the following description into the text area:
location of contact or technician
- For the
location
parameter, click Click to add an example. - Insert the following description into the text area:
39.355589 -120.652492
- Click Responses.
- Click Add Response.
- Leave the response as 200 - OK.
- Click Add Media Type.
- Leave the Media Type as
application/json
. - 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" ] }
- Scroll upward and click Add Response again.
- Scroll back down, and for the new response select 404 - Not Found.
- Scroll back to the top click Save.
Now we'll create a POST to add a new incident to the collection.
- Click Add Method and select POST.
- For the
POST
method, click Add Media Type. - Select
application/json
. - 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" }
- For the
POST
method, click Responses and then Add Response. - Select 201 - Created.
- Click Add Media Type
and select
application/json
. - Scroll back up and click Save.
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.
- In the menu on the left, click Mobile Backends. (If you have hidden the menu, click and select Applications > Mobile Backends.)
- Select the
incidentreports
backend and click Open. - In the left navigation area for the
incidentreports
mobile backend, click APIs. - Click Select APIs.
- For the Incident Report API, click the icon.
Test 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.
- Navigate back to the API designer by clicking Applications > APIs in the main menu. (If you have hidden the menu, click and then select Applications > APIs.)
- Select the Incident Report API and click Test.
- Click Default API Designer Test Credentials.
- 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.
- 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.
- For the
POST /incidents
endpoint, click Test Console and then click Use Example. - Click Test Endpoint.
In the Response Status section, you should see a 201 code and the example data you entered when defining the API.
Implement 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.
- Navigate back to the API designer by clicking Applications > APIs in the main menu. (If you have hidden the menu, click and then select Applications > APIs.)
- Select the Incident Report API and click Open.
- Click Implementations.
- Click JavaScript Scaffold to download the scaffold.
- On your system, unzip the scaffold file.
- 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); }); };
- 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. - (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.
- Run
npm install
within the directory containing thepackage.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.) - Create a zip file of these artifacts, including the root
folder containing the
package.json
file.You can name the zip anything you want.
- In the API designer, open the
incidentreport
API. - In the left navigation bar, click Implementations.
- 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.
Test the implementation
Now that you have uploaded an implementation, you can test the API against that implementation.
- On the Implementations page, click Test.
- 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.
- In the Endpoints page, navigate to
POST/incidents
, click Test Console and then click Use Example. - 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.
- In the menu on the left, click Mobile Backends. (If you have hidden the menu, click and select Applications > Mobile Backends.)
- Double-click your mobile backend.
- Click Diagnostics.
- Click Logs.
- 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.
Next steps
- Learn the fine points of designing custom APIs.
- Learn more about writing custom code.
- Learn how to call MCS platform APIs from custom code.