How to Invoke HCM REST Services using JavaScript

Overview

The Fusion HCM Cloud provides RESTful API services to interact with key business objects.  This article describes how to invoke these services using JavaScript and HTML.

The example focuses on the HCM Employee REST service and provides examples on how to fetch, filter response data and limit the number of records returned.  HCM Restful APIs are one of the three methods to Load data within HCM Cloud, other two are – HCM Data Loader aka HDL and HCM Spreadsheet Data loader aka HSDL. 

Latest document on total available REST API’s can be found at- 

https://docs.oracle.com/en/cloud/saas/global-human-resources/19c/farws/index.html

Use Case discussed

This article will describe a simple HTML Page which will call the HCM RESTful API to fetch the employee data using the Java script and will display on the same page.

How to

This article will describe how we achieved it using the two simple Java function call as follows:

  1. invokeService
  2. sendGetRequest
  • Invoke Service:

This is the main function that is called to invoke HCM REST Services.  The function builds the request URI (Universal Resource Identifier) using the server, endpoint and query string and displays the formatted URI string in the browser console and in the requestDiv element. 

A handler is created that will be called when the complete response from the service is received.  The response handler calls the JSON parse function to convert the response text to a JavaScript object.  The code uses this object to retrieve the number of records returned in the response. The handler also calls the JSON stringify function to convert the response to a more readable string.  The string is then formatted so that it can be properly displayed in HTML. The number of records retrieved, and the formatted response are logged to the browser console and displayed in the responseDiv element.

Click for code

ParametersDescription
ServerThe server/host name
EndpointThe Rest Endpoint
QuerystringThe HTML query string.  This string can include query parameters and a variety of filters that control the response from the service.
username    The fusion cloud user with privileges to invoke REST APIs
PasswordUser Password
requestDivDOM element to display the request URI
responseDivDOM element to display the formatted response
ReturnThis function does not return anything and acts as a wrapper
  • sendGetRequest:

This function does the work of sending an HTTP GET request to the Rest endpoint on the server (the URI).  This will first call a function to create an XMLHttpRequest object. The XMLHttpRequest object is used to send an asynchronous request to the server.  The onreadystatechange function is created and assigned to the request object. This function will be called asynchronously as response data is returned.  We pass our handler as a parameter to this function, creating what’s known as a closure in JavaScript. This is to ensure that the response handler function we created in the invokeService function and passed to this function will remember the variables referenced (e.g. responseDiv) when the handler was created.  

The onreadystatechange function is called progressively each time state changes.  The meaning of each state is as follows:

0 – UNSENT

1 – OPENED

2 – HEADERS_RECEIVED

3 – LOADING

4 – DONE

When the state changes to 4, communication with the server is complete.  The HTTP status is also returned along with each state change. If the request is complete (state = 4 or XMLHttpRequest.DONE) and the HTTP status is 200 (Success), then we call the handler method passing the responseText as a parameter to us to display the response in our HTML page. 

Note: Since the content type is set to application/json the response is returned in XMLHttpRequest.responseText NOT XMLHttpRequest.responseXML.

Next, we call the XMLHttpRequest open method to initialize the request with the HTTP GET method and the URI.  The last parameter to this method indicates how the request should be processed. Passing null indicates we want to process the response asynchronously.

Once the request is initialized, we can set the credentials in the Authentication HTTP header.  We call our setCredentials function to accomplish this. 

Note: There is a variation of the XMLHttpRequest open method that accepts a username and password.  The HCM REST services expect these values to be concatenated and base64 encoded, so we must set them explicitly.

Finally, we send the request to the server.  We pass null to the XMLHttpRequest send method because we are sending a GET request.  If this were a POST request, we would send the POST data as a parameter.

ParametersDescription
uri         The request URI
username    The fusion cloud user with privileges to invoke REST APIs
PasswordUser Password
handler     the response handler function
ReturnThis function does not return anything and acts as a wrapper

Click for code

Invoke from HTML

Here we will see how to invoke the HCM Employee REST service with some commonly use used cases:

  • Example 1: No query string specified

querystring = ”

Since there are no query parameters or filters specified, all employees will be returned.  The service will only retrieve the first 25 records. All data and links associated with the employee object will also be retrieved.

  • Example 2: retrieve selected fields and no links

querystring = ‘?fields=LastName,FirstName,PersonId&onlyData=true’

This example sets filters to identify the fields you want returned in the response.  It also specifies that only data, not links, should be returned. Multiple filters are separated by the & symbol.  This request will return the LastName, FirstName and PersonId for the first 25 employees. No links will be returned in the response.

  • Example 3: limit the number of records returned

querystring = ‘?fields=LastName,FirstName,PersonId&onlyData=true&limit=5’

This example does the same thing as the previous example but sets a filter to limit the number of records returned to 5.

  • Example 4: query for specific records 

querystring =’?q=LastName=Miller’

This example sets a query parameter to retrieve employee records where the LastName is Miller.  All data and links will be returned.        

  • Example 6: query for specific records and filter the results

querystring = ‘?q=LastName=Miller&fields=LastName,FirstName,PersonId&onlyData=true’

This example adds filters to the to the previous example.  Only the LastName, FirstName and PersonId will be returned for records where the LastName is Miller.  No links are returned. 

Code Units

invokeService

*/
function invokeService(server, endpoint, querystring, username, password, requestDiv, responseDiv) {

    var uri = server + endpoint,
    handler = function() {
        return function (data) {
            var nRecs = '', obj, str;
            if (data) {
                obj = JSON.parse(data);
                str = JSON.stringify(data);
                str = str.substring(1, str.length - 1)
                           .replace(/\\n/g, '<br/>')
                           .replace(/\\"/g, '"');

                if (obj && obj.count) {
                    nRecs = 'Number of records returned: ' + obj.count;
                    console.log(nRecs);

                    nRecs = nRecs + '<p>More records available? ' + (obj.hasMore ? 'Yes' : 'No') + '</p>';
                }

                str = (nRecs ? '<p>' + nRecs + '</p>' + str : str);
            }
            else {
                str = 'An error occurred.  Ensure the Request URI, username and password are correct';
            }

            console.log(data ? data : str);

            responseDiv.innerHTML = str; 
        };
    }();

    if (querystring) {
        uri = uri + querystring; 
    }

    requestDiv.innerHTML = uri;

    sendGetRequest(uri, username, password, handler);
}

/*

sendGetRequest

*/
function sendGetRequest(uri, username, password, handler) {
    var req = getXmlRequest()
    if (req == null) {
        console.log('Failed to get XMLHttpRequest object');
        return;
    }
    req.onreadystatechange = function(fn) {
        return function () {
            var status = ('readyState: ' + req.readyState + ', ' + 
                          'status: ' + req.status + ' ' + req.statusText);
            console.log(status);

            if (req.readyState === XMLHttpRequest.DONE) {
                if (req.status === 200) {
                    fn(req.responseText);
                }
                else {
                    fn('');
                }            
            }
        };
    }(handler);
    req.open('GET', uri, true);
    if (username && password) {
        setCredentials(req, username, password);
    }
    req.send(null);
}
/*

Other Ancillary Code Units

  • setCredentials

This function base64 encodes the username and password and sets the resulting string in the HTTP Basic Authentication header.

ParametersDescription
req         The initialized XMLHttpRequest object
username    The fusion cloud user with privileges to invoke REST APIs
PasswordUser Password


ReturnThis function does not return anything and acts as a wrapper
  • getXmlRequest

This function creates and returns an XMLHttpRequest object that is compatible with the user’s browser.

ParametersDescription
ReturnsXMLHttpRequest object
*/
function getXmlRequest() {
    var e1, e2;

    if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    } 
    else if (window.ActiveXObject) {
        try {
            return new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e1) {
            try {
                return new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e2) {
                // fall through
            }                    
        }
    } 
    return null;
}

Leave a Reply

Your email address will not be published. Required fields are marked *