Part 9: Implement custom APIs


Options



Fix it Fast Scenario: Table of Contents

Before You Begin

Purpose

In this part of the tutorial, you write JavaScript code to implement APIs that have been defined by a RAML document.

An API implementation can call MCS platform APIs (such as Storage and Notifications), other custom APIs, and external REST and SOAP web services. The implementation can access external web services directly or through MCS connectors.

The coding model is based on Node.js, which is a lightweight JavaScript framework that enables you to write and run server-side code. For each API endpoint, which is the URI plus the HTTP request method (such as GET or POST), you write a route definition that specifies how to respond to a client request to that endpoint.

Route definitions follow the coding style promoted by Express.js, which is a library that extends Node.js. You do not need to create full Node.js applications when you use the custom code service. You simply need to add route definitions for the API’s endpoints.

After you have written the custom code, you package it as a Node.js module and upload it to MCS.

Step 1: Implement the API with JavaScript Node.js

In this section, you implement an incident reporting API by downloading a JavaScript scaffold that contains stub implementations for your endpoints, adding code to the stub implementations, and uploading your changes to MCS.

  1. Log on to your MCS instance and click the Development button.

    Sample chart
  2. In the Developer Portal, click the APIs icon.

    Sample chart
  3. Find the FIF_IncidentReport_xx API and open it.

    Sample chart
  4. On the left, click the Implementations icon and then click the JavaScript Scaffold button to download the skeleton code.

    The JavaScript scaffold contains stub implementations for your endpoints. It is generated from the RAML that is associated with the API.

    Sample chart
  5. The scaffold comes in the form of a zip file that contains the following files. Download and unzip the file.

    - incidentreport_xx.js: JavaScript skeleton code that contains stub implementations to match the RAML resource methods.

    - package.json: The standard package.json file. The name, version, and main sections are mandatory. The 'apis' and 'connectors' sections hold a list of dependencies.

    - ReadMe.md: Descriptions of the incidentreport.js and package.json files.

    - samples.txt: Some custom code examples.

    Take a look at the JavaScript and JSON files. In this lesson, you edit, repackage, and upload these files to MCS.

    Open the incidentreport_xx.js file in an editor.

    Sample chart
  6. In the incidentreport_xx.js file, notice that the JavaScript functions match the MCS API definition.

    In the Code:

    Sample chart

    In MCS:

    Sample chart
  7. Modify the JavaScript to add notes and display values.

    In the incidentreport_xx.js file, locate the definition that starts with service.get('/mobile/custom/incidentreport_xx/incidents/:id/status'.

    Modify the code by adding the following lines:

    result.code = "New";
    result.notes = "This is a note.";
    console.log("returning " + JSON.stringify(result));

    Sample chart
  8. Locate the definition that starts with service.get('/mobile/custom/incidentreport_xx/incidents',.

    Modify this definition, as shown in the following code sample. The code can be found in the labfiles/code/IncidentReportExample.txt file.

    var result = [];
    var incident1 = {};
    incident1.id = 1;
    incident1.username = "user1";
    incident1.title = "Incident 1";
    incident1.notes = "Note 1";
    var incident2 = {};
    incident2.id = 2;
    incident2.username = "user2";
    incident2.title = "Incident 2";
    incident2.notes = "Note 2";
    result.push(incident1);
    result.push(incident2);

    The code in this sample does the following:

    1: Changes the result to an array
    2: Creates two JavaScript objects, and sets the id, username, title, and notes properties in each object
    3: Adds the objects to the result array

    Your code should look like the following.

    Sample chart
  9. After saving all your work, create a zip file that includes all four files and the directory. Name the file incidentreport_xx.zip (where _xx are the unique characters for your API).

    Sample chart
  10. Back in the MCS API implementation page, at the bottom, click Upload an implementation archive.

    In the Open window, select the zip file that you just created.

    Then click Open.

    Sample chart
  11. Close the dialog window and you can see that the JavaScript you added is now part of the implementation.

    Sample chart
  12. With the implementation selected, click the Test button.

    Sample chart
  13. Test the code that you added for getting the status of an incident. Select the GET /incidents/{id}/status endpoint and enter the following values:

    Parameters

    id: 15

    Authentication:
    Mobile Backend: FIF_Technician_xx
    Version: 1.0
    Username: joe_xx
    Password: Use the password that you received by email when you created the user.

    Then click the Test Endpoint button.

    Sample chart
  14. The request should return a response status of 200, and the response should contain the code and notes that you specified earlier.

    Sample chart
  15. Next, you test the code that you added for getting incidents. Select the GET /incidents endpoint and enter the following values.

    Authentication
    Mobile Backend: FIF_Technician_xx
    Version: 1.0
    Username: joe_xx
    Password: Use the password that you received by email when you created the user.

    Then click the Test Endpoint button

    Sample chart
  16. The request should return a response status of 200, and the response should include the content of the two objects that you specified earlier

    Sample chart

Step 2: Include the RightNow connector in custom API code

In this part of the tutorial, you enable your custom code to access a SOAP service by using the SoapRightNow connector that you created earlier. The connector will allow the API to access real data from the RightNow service.

  1. First set the API to use the SoapRightNow connector. From the zip file that you worked on earlier, find the package.json file and open it in an editor.

    In the connectors area, add an entry that matches the name and version of the connector that you created in MCS (remember to use your two character suffix). For example:

    "/mobile/connector/SoapRightNow_xx":"1.0"

    In the Code:

    Sample chart

    In MCS:

    Sample chart
  2. Next, access the SoapRightNow connector from your JavaScript.

    From the zip file, open the incidentreport_xx file in an editor. Edit the POST method to include code to access the service. The code specifies the format of the response and converts the payload to a JSON string by calling the JSON.stringify operation.

    Replace the code in the body of the service.post('/mobile/custom/incidentreport_xx/incidents', function(req,res) stub implementation with the following code. Also remember to replace _xx in the optionslist.uri variable with your two character suffix. The code can be found in the labfiles/code/IncidentPOST.txt file.

    var handler = function(error, response, body){
    var responseMessage = body;
    if (error){
    responseMessage = error.message;
    }
    res.status(response.statusCode).send(responseMessage);
    res.end;
    };
    var optionsList = {};
    optionsList.uri = '/mobile/connector/SoapRightNow_xx/CreateIncident';
    optionsList.headers={'content-type' : 'application/json;charset=UTF-8'};
    var payload = { Header: null, Body: {CreateIncident: req.body}};
    optionsList.body=JSON.stringify(payload);
    req.oracleMobile.rest.post(optionsList,handler);

    Sample chart
  3. Next, add code to the GET method to use the SoapRightNow connector.

    In the incidentreport_xx.js file, find the service.get('/mobile/custom/incidentreport_xx/incidents/:id', function getincidentById(req,res) method and replace the body with the following code. This code performs functions that are similar to the code that you added to the POST method. The code can be found in the labfiles/code/IncidentGETbyID.txt file.

    Replace _xx in the optionslist.uri variable with your two character suffix.

    var handler = function(error, response, body){
    var responseMessage = JSON.parse(body);
    if (error){
    res.send(500, error.message);
    }
    res.type(response.headers['content-type']);
    res.send(response.statusCode, responseMessage);
    };
    var optionsList = {};
    optionsList.uri = '/mobile/connector/SoapRightNow_xx/GetIncidentById';
    optionsList.headers={'content-type' : 'application/json;charset=UTF-8'};
    var payload = {Header: null, Body: {"GetIncidentById": {"IncidentId": req.params.id}}};
    optionsList.body = JSON.stringify(payload);
    req.oracleMobile.rest.post(optionsList,handler);

    Sample chart
  4. Save your work.

  5. As you did earlier, create a zip file that contains the package.json, incidentreport_xx.js, ReadMe.md, and samples.txt files.

    Sample chart
  6. In MCS, navigate back to your FIF_IncidentReport_xx API and click the Implementations icon.

    Sample chart
  7. Scroll down and click Upload an implementation archive.

    Find and select your zip file. Then click Open.

    Sample chart
  8. Dismiss the message, and click the Test button.

    Sample chart
  9. In the Endpoints page, navigate to POST/incidents and expand the Parameters node.

    Populate the request body by clicking the Use Example button.

    Set the UserName to shea (or use whatever name you want to use).

    Expand the Authentication node and set the following values:

    Mobile Backend: FIF_Technician_xx
    Version: 1.0
    Username: joe_xx
    Password: Use the password that you received by email when you created the user.

    Sample chart
  10. Then, click the Test Endpoint button and wait for a response.

    You should see a new incident id returned (the incident id in the example is 14).

    Sample chart
  11. Next, use the GET method to return the incident that you just created.

    In the Endpoints page, navigate to GET /incidents/{id}.

    Expand the Parameters node and set the id to the IncidentId value that was returned in the previous step.

    Then set the authorization to the same values that you used when you tested the POST method.

    Sample chart
  12. Click the Test Endpoint button and examine the results.

    You should see the incident record that was created when you tested the POST method. Confirm that the incident uses the username that you specified earlier. The username in the example is "shea".

    Sample chart
  13. The last method that you need to implement is GET incidents, which returns more than one record. The code that you add does a few things.

    First, because there are two ways to return incidents, either by contact or by technician, you need to determine which way is used. You do this by using req.query to get the value of the query parameter that was passed to the request. You also need to convert the payload to a JSON string by calling the JSON.stringify operation. Then, you use POST from the SDK to execute the request.

    Open the incidentreport_xx.js file in an editor and find the service.get('/mobile/custom/incidentreport_jg/incidents', function(req,res) stub implementation. The code can be found in the labfiles/code/IncidentGETbyCUSTOMER.txt file.

    Replace _xx in the optionslist.uri variable with your two character suffix.

    Then, replace the body with the following code:

    var handler = function(error, response, body){
    var responseMessage = JSON.parse(body);
    if (error){
    res.send(500, error.message);
    }
    res.status(response.statusCode).send(responseMessage);
    res.end;
    };
    var optionsList = {};
    var payload = {};
    if (req.query.contact){
    optionsList.uri = '/mobile/connector/SoapRightNow_xx/GetIncidentsByCustomer';
    payload = {Header: null, Body: {"GetIncidentsByCustomer": {"UserName": req.query.contact}}};
    }
    else if (req.query.technician){
    optionsList.uri = '/mobile/connector/SoapRightNow_xx/GetIncidentsByTechnician';
    payload = {Header: null, Body: {"GetIncidentsByTechnician": {"TechnicianEmailAddress": req.query.technician}}};
    }
    optionsList.headers={'content-type' : 'application/json;charset=UTF-8'};
    optionsList.body=JSON.stringify(payload);
    req.oracleMobile.rest.post(optionsList,handler);

    Sample chart
  14. Save your changes.

    Create a zip file that contains the implementation files and then upload the new implementation to MCS.

    Sample chart
  15. Click the Test button and navigate to the GET/incidents method.

    In the Parameters node, set the technician to joe@fixit.com.

    Then in the Authentication node, select your mobile backend. The version should default to 1.0. Use joe_xx as the user name and enter the password that you received by email when you created the user.

    Sample chart
  16. Then, click the Test Endpoint button.

    You should see a Response Status of 200 and a few records, all containing joe@fixit.com as the assigned technician.

    Sample chart

Step 3: Access the API by using the MAF MCS Tester Application

In this part of the tutorial, you test the API implementation by using the MAF MCS Tester Application.

  1. Go back to the MAF MCS Tester Application and navigate to the Home page, as shown in the following image.

    Then, click the MCS Custom API option.

    Sample chart
  2. From this page, you can run any API methods that joe_xx is authorized to run.

    You must set two properties to run the API: URI and HTTP Method.

    Sample chart
  3. First set the URI. You can find the value for this field by looking at the API endpoints in MCS.

    Back in MCS, open the FIF_IncidentReport_xx API in the API Designer.

    Then click the Test button.

    Sample chart
  4. Here you see all the methods that you can use. Each method has a unique URL that you can use when you test the API.

    Sample chart
  5. First, you test the GET/incidents method to see the service return a few records from the database.

    Look at the GET/incidents endpoint. The URI that you need to use in the tester consists of everything that follows the port number.

    In the example, the URI is:

    /mobile/custom/incidentreport_jg/incidents

    Sample chart
  6. Go back to the MAF MCS Tester Application, and in the CUSTOM API TESTER FORM section, enter the value in the URI field.

    Sample chart
  7. By default, the HTTP Method is set to the first method in the list, GET. You test the GET method first.

    Instead of returning all incidents, you can include a query parameter in the URL to restrict the records that are returned. Query parameters are constructed by including a "?", followed by the parameter name and then the parameter value.

    To only return incidents where the contact is lynn, append the following query parameter to the URI:

    /?contact=lynn

    Sample chart
  8. At the bottom of the form, click Invoke Custom API to run the API and test the method using the URI that you specified.

    Sample chart
  9. The API runs, and you should see records returned at the bottom of the page. These records come from the API, which is implemented using JavaScript to access the connector for the RightNow service.

    The response should include at least one record. Find one and look for the Id. In my case it was 32 but your number may differ. You can scroll down to see other records.

    Sample chart
  10. Next, you test a different method. This time, instead of using query parameters to return a record, you specify a value as part of the path.

    In MCS, go back to the API tester and find the GET/incident/{id} endpoint.

    Locate the URI (everything that follows the port number). For example:

    /mobile/custom/incidentreport_jg/incidents/{id}

    Sample chart
  11. Go back to the MAF MCS Tester Application, and in the CUSTOM API TESTER FORM section, enter the value in the URI field.

    Sample chart
  12. Before you run the API, you need to set the Id.

    In the URI field, delete the {id} expression and replace it with the Id value that was returned earlier form the GET. In my case it was, 32. For example:

    /32

    Sample chart
  13. Then, at the bottom of the form, click Invoke Custom API to run the API.

    The response should include only one record, the incident with an Id of 32.

    Sample chart

Fix it Fast : Table of Contents