Skip to main content

REST.V2

REST (Representational State Transfer) and RESTful applications use HTTP requests to post data (create and update), read data (make queries), and delete data.

The REST.V2 Moobot module accesses an external RESTful API through HTTP or HTTPS, offering consistent usage between the available methods and customization of HTTP requests sent.

It supports asynchronous operation (using callback functions) to send a request without blocking the JavaScript code execution until the request is completed. It supports use of the timeout property to make the request fail after a specified time.

REST.V2 is available to load into any standard Moobot.

To use, define a new global variable at the top of a Moobot JavaScript file to load the module. For example:

var REST = MooBot.loadModule('REST.V2'); 

Reference Guide

sendGet

Sends a HTTP GET request to a third party (URL) with optional parameters:

Request Arguments

Name

Type

Description

url

String

The request URL. Mandatory

<parameters>

JSON Object

Optional parameters. See below

Optional parameters

Name

Type

Description

params

String or Object

Either a String with the request encoded parameters or an Object with the parameters that will get encoded by the module.

user 

String

The user name for basic authentication.

password

String

The password for basic authentication.

encrypted_password

String

Encrypted version of password (encrypted using moog_encryptor).

disable_certificate
 _validation

Boolean

'true' to disable HTTPS server certificate validation by the Moobot.

headers

Object

Any additional headers sent with the request.

callback 

Callback function

The request is sent asynchronously, returns null and the callback function is called regardless of the success or failure of the request. See below.

success

Callback function

The request is sent asynchronously, returns null and the success function is called only the request was successful. See below.

failure

Callback function

The request is sent asynchronously, returns null and the failure function is called only if the request failed. See below.

timeout

Number

The period of time (in seconds) to wait for response before completing with timeout error.

If 0 or less, wait indefinitely. The default is 120 seconds.

proxy

String or Object

Host, port, user, encrypted_password/password.

For example, as an object:

proxy:{  
    host:"proxyhost",
    port:1223,
    user:"proxyuser",
    encrypted_password:"2KctaEbJH/m8rz4WqgmZYZfdripdIsku7fOFJWM6YNA="
    //password: "unencrypted_plain_text_password"
}

As an object, you can either specify a Moogsoft encrypted password or a plain text password, specifying both will favour the encrypted_password value.

Or, as a string, where format is <user>:<password>@<host>:<port>

proxy: "proxyuser:passw0rd@proxyhost:1223"

Only plain text passwords are supported in the string format.

Sending an asynchronous request (with callback functions)

To send a request without blocking the javascript code execution until the request is completed, define one (or more) of the callback functions: callback, success and failure. The REST.V2 module method (send...) then returns null, and sends the request in another thread.

Return Parameters

Sending a synchronous request returns a JavaScript object with the following fields:

Name

Type

Description

success

Boolean

True if and only if the request was successful

status_code

Number

The HTTP status code of the request

(200 = OK, 404 = Not found. Full list at w3.org)

status_msg

String

The message from the request ("OK", "Not found", etc.)

response

String

The response as raw text

Currently, binary response is not supported

headers

Object

The response HTTP headers

Sending an asynchronous request (with callback functions) returns null. Once the request has completed, the callback function(s) are called with the reply object as the first (optional) parameter and the request object as the second (optional) parameter.

Examples

Each of the following gives details on the Moogsoft home page:

Synchronous request

var rc = REST.sendGet('http://www.Moogsoft.com');

Asynchronous request

function restSuccess(rc)
{
    var response = JSON.parse(rc.response);
    logger.info("number = " + response.records[0].number);
}
 
function restFailed(rc, req)
{
    var response = JSON.parse(rc.response);
    logger.info("URL:" + req.url +" failed - Msg:" + response.status_msg);
}
 
REST.sendGet({url: "http://www.Moogsoft.com",
                           success: restSuccess,
                           failure: restFailed});

Response

{
    "status_code": 200,
    "success": true,
    "response": "<!DOCTYPE html>... </body></html>",
    "status_msg": "OK",
    "headers": {
        "Transfer-Encoding": [
            "chunked"
        ],
        "Keep-Alive": [
            "timeout=15, max=100"
        ],
        "Server": [
            "Apache/2.2.22 (Ubuntu) PHP/5.3.10-1ubuntu3.10 with Suhosin-Patch mod_ssl/2.2.22 OpenSSL/1.0.1"
        ],
        "Connection": [
            "Keep-Alive"
        ],
        "Vary": [
            "Accept-Encoding"
        ],
        "Date": [
            "Fri, 30 Jan 2015 12:37:13 GMT"
        ],
        "Content-Type": [
            "text/html"
        ],
        "X-Powered-By": [
            "PHP/5.3.10-1ubuntu3.10"
        ]
    }
}

sendPost

Sends a HTTP POST request to a third party (URL) with optional parameters:

Request Arguments

Name

Type

Description

url

String

The request URL. Mandatory

<parameters>

JSON Object

Optional parameters. See below

Optional parameters

Name

Type

Description

params

String or Object

Either a string with the request encoded parameters or an object with the parameters that will get encoded by the module.

content_type

String

The content type of the body.

body

String or Object

The request body. Either a string (that will be sent as is) or an object. If the content_type is “application/json” and the body is an object, the body will be sent as JSON. Otherwise it will be sent as URL encoded.

user 

String

The user name for basic authentication.

password

String

The password for basic authentication.

encrypted_password

String

Encrypted version of password (encrypted using moog_encryptor).

disable_certificate
 _validation

Boolean

'true' to disable HTTPS server certificate validation by the Moobot.

headers

Object

Any additional headers sent with the request.

callback 

Callback function

The request is sent asynchronously, returns null and the callback function is called regardless of the success or failure of the request. See below.

success

Callback function

The request is sent asynchronously, returns null and the success function is called only the request was successful. See below.

failure

Callback function

The request is sent asynchronously, returns null and the failure function is called only if the request failed. See below.

timeout 

Number

The period of time (in seconds) to wait for response before completing with timeout error.

If 0 or less, wait indefinitely. The default is 120 seconds.

proxy

String or Object

Host, port, user, encrypted_password/password.

For example, as an object:

proxy:{  
    host:"proxyhost",
    port:1223,
    user:"proxyuser",
    encrypted_password:"2KctaEbJH/m8rz4WqgmZYZfdripdIsku7fOFJWM6YNA="
    //password: "unencrypted_plain_text_password"
}

As an object, you can either specify a Moogsoft encrypted password or a plain text password, specifying both will favour the encrypted_password value.

Or, as a string, where format is <user>:<password>@<host>:<port>

proxy: "proxyuser:passw0rd@proxyhost:1223"

Only plain text passwords are supported in the string format.

Sending an asynchronous request (with callback functions)

To send a request without blocking the JavaScript code execution until the request is completed, define one (or more) of the callback functions: callback, success and failure. The REST.V2 module method (send...) then returns null, and sends the request in another thread.

Return Parameters

Sending an asynchronous request (with Callback functions) returns null. See above.

Sending a synchronous request returns a JavaScript object with the following fields:

Name

Type

Description

success

Boolean

True if and only if the request was successful.

status_code

Number

The HTTP status code of the request.

(200 = OK, 404 = Not found. Full list at w3.org)

status_msg

String

The message from the request ("OK", "Not found", etc.)

response

String

The response as raw text. Binary response is not supported.

 headers

Object

The response HTTP headers.

Sending an asynchronous request (with callback functions) returns null. Once the request has completed, the callback function(s) are called with the reply object as the first (optional) parameter and the request object as the second (optional) parameter.

Examples

Each of the following accesses DuckDuckGo and searches for 'Moogsoft'.

Synchronous request:

var rc = REST.sendPost('https://api.duckduckgo.com/',
{q:'Moogsoft', format:'json', pretty:1});

Asynchronous request:

REST.sendPost({url: 'https://api.duckduckgo.com/',
   body: {q:'Moogsoft', format:'json', pretty:1},
   timeout: 4.2,
   callback: function(rc) {
   ...
   }});

Here, the request has a timeout set of 4.2 seconds.

Responses

For the synchronous request, and for the asynchronous request if it doesn't time out:

{
    "status_code": 200,
    "success": true,
    "response": "{   \"DefinitionSource\" : \"\",   \"Heading\" : \"\",   \"ImageWidth\" : 0,   ... : \"\"}",
    "status_msg": "OK",
    "headers": {
        "Transfer-Encoding": [
            "chunked"
        ],
        "Strict-Transport-Security": [
            "max-age=0"
        ],
        "Cache-Control": [
            "max-age=1"
        ],
        "Server": [
            "nginx"
        ],
        "X-DuckDuckGo-Results": [
            "1"
        ],
        "X-DuckDuckGo-Locale": [
            "en_US"
        ],
        "Connection": [
            "keep-alive"
        ],
        "Expires": [
            "Fri, 30 Jan 2015 12:44:47 GMT"
        ],
        "Date": [
            "Fri, 30 Jan 2015 12:44:46 GMT"
        ],
        "Content-Type": [
            "application/x-javascript"
        ]
    }
}

...if the asynchronous request times out:

{
    "status_code": 408,
    "success": false,
    "status_msg": "Request Time-Out"
}

sendPut

Sends a HTTP PUT request to a third party (URL) with optional parameters:

Request Arguments

Name

Type

Description

url

String

The request URL. Mandatory.

<parameters>

JSON Object

Optional parameters. See below.

Optional parameters

Name

Type

Description

params

String or Object

Either a string with the request encoded parameters or an object with the parameters that will get encoded by the module.

content_type

String

The content type of the body.

body

String or Object

The request body. Either a string (that will be sent as is) or an object. If the content_type is “application/json” and the body is an object, the body will be sent as JSON. Otherwise it will be sent as URL encoded.

user 

String

The user name for basic authentication.

password

String

The password for basic authentication.

encrypted_password

String

Encrypted version of password (encrypted using moog_encryptor).

disable_certificate
 _validation

Boolean

'true' to disable HTTPS server certificate validation by the Moobot.

headers

Object

Any additional headers sent with the request.

callback

Callback function

The request is sent asynchronously, returns null and the callback function is called regardless of the success or failure of the request. See below.

success

Callback function

The request is sent asynchronously, returns null and the success function is called only the request was successful. See below.

failure

Callback function

The request is sent asynchronously, returns null and the failure function is called only if the request failed. See below.

timeout

Number

The period of time (in seconds) to wait for response before completing with timeout error.

If 0 or less, wait indefinitely. The default is 120 seconds.

Sending an asynchronous request (with callback functions)

To send a request without blocking the JavaScript code execution until the request is completed, define one (or more) of the callback functions: callback, success and failure. The REST.V2 module method (send...) then returns null, and sends the request in another thread.

Return Parameters

Sending a synchronous request returns a JavaScript object with the following fields:

Name

Type

Description

success

Boolean

True if and only if the request was successful.

status_code

Number

The HTTP status code of the request.

(200 = OK, 404 = Not found. Full list at w3.org)

status_msg

String

The message from the request ("OK", "Not found", etc.)

response

String

The response as raw text.

Binary response is not supported.

headers

Object

The response HTTP headers.

Sending an asynchronous request (with callback functions) returns null. Once the request has completed, the callback function(s) are called with the reply object as the first (optional) parameter and the request object as the second (optional) parameter.

Example

The following stores the specified information at the URL (similar to a file upload):

Request

var rc = REST.sendPut('http://api.acme.com/reportIncident', '{"incident":"broken fan","location":"office2"}');

Response

{
    "status_code": 204,
    "success": true,
    "response": "",
    "status_msg": "No Content",
    "headers": {
        "Connection": [
            "keep-alive"
        ],
        "Date": [
            "Fri, 30 Jan 2015 12:55:59 GMT"
        ]
    }
}

When POSTing or PUTting URL encoded data (a content-type of "application/x-www-form-urlencoded”) complex objects will need to be either split into individual key:value pairs suitable for url encoding or simply JSON stringify the object in its entirety. Stringifying the object will require the receiver to be able to parse the string value back to an object if needed. If the receiver cannot do this parsing then the object will need to be broken into key value pairs. For example, to send the entire alert custom_info object as part of a URL-encoded body:

 var custom_info = alert.getCustomInfo();
 var payload;
 try {
 payload = JSON.stringify(custom_info);
 }
 catch(e) {
 logger.info(“Failed to stringify custom_info “ + e );
 payload = null;
 }


        var postParams={
            "url" : “http://www.someurl.com/someEndpoint",
            "body" : payload,
            "content_type" : "application/x-www-form-urlencoded”
 };
 
 var request = rest.sendPost(postParams);

sendDelete

Sends an HTTP DELETE request to a third party (URL) with optional parameters:

Request Arguments

Name

Type

Description

url

String

The request URL. Mandatory.

<parameters>

JSON Object

Optional parameters. See below.

Optional parameters

Name

Type

Description

params

String or Object

Either a string with the request encoded parameters or an object with the parameters that will get encoded by the module.

user 

String

The user name for basic authentication.

password

String

The password for basic authentication.

encrypted_password

String

Encrypted version of password (encrypted using moog_encryptor).

disable_certificate
 _validation

Boolean

'true' to disable HTTPS server certificate validation by the Moobot.

headers

Object

Any additional headers sent with the request.

callback

Callback function

The request is sent asynchronously, returns null and the callback function is called regardless of the success or failure of the request. See below .

success

Callback function

The request is sent asynchronously, returns null and the success function is called only the request was successful. See below.

failure

Callback function

The request is sent asynchronously, returns null and the failure function is called only if the request failed. See below.

timeout

Number

The period of time (in seconds) to wait for response before completing with timeout error.

If 0 or less, wait indefinitely. The default is 120 seconds.

Sending an asynchronous request (with callback functions)

To send a request without blocking the javascript code execution until the request is completed, define one (or more) of the callback functions: callback, success and failure. The REST.V2 module method (send...) then returns null, and sends the request in another thread.

Return Parameters

Sending a synchronous request returns a JavaScript object with the following fields:

Name

Type

Description

success

Boolean

True if and only if the request was successful.

status_code

Number

The HTTP status code of the request.

(200 = OK, 404 = Not found. Full list at w3.org)

status_msg

String

The message from the request ("OK", "Not found", etc.)

response

String

The response as raw text.

Binary response is not supported.

 headers

Object

The response HTTP headers.

Sending an asynchronous request (with callback functions) returns null. Once the request has completed, the callback function(s) are called with the reply object as the first (optional) parameter and the request object as the second (optional) parameter.

Example

The following sends a delete request to the specified URL, with additional headers criteria:

Request:

var rc = REST.sendDelete({url:"http://moogbox2:9090/deletePassport/123456789","headers":{"user-agent":"moobot","accept":"text/plain","accept-language":"en-US"}});;

Response

{
    "status_code": 200,
    "success": true,
    "response": "{\t\"remoteId\": 33,\t\"weight\": 0.8240487528964877,\t\"location\": {\t\t\"latitude\": 147.3387699946761,\t\t\"longitude\": -7.957067163661122\t}}",
    "status_msg": "OK",
    "headers": {
        "Transfer-Encoding": [
            "chunked"
        ],
        "Connection": [
            "keep-alive"
        ],
        "Date": [
            "Fri, 30 Jan 2015 12:49:44 GMT"
        ],
        "Content-Type": [
            "application/json"
        ]
    }
}

send

A generic send request for sending other HTTP methods as part of the request properties ('GET', 'HEAD', etc.). Optional parameters for synchronous and asynchronous requests are available as described in the above methods.

Example

The following returns time/date information from the Moogsoft server:

Request

var rc = REST.send({method: 'HEAD', url: 'http://www.Moogsoft.com/'});
logger.warning("rc: " + JSON.stringify(rc, null, "\t") );
var date = rc.headers.Date[0];
logger.warning("date " + date );

Response

{
    "status_code": 204,
    "success": true,
    "response": "",
    "status_msg": "OK",
    "headers": {
        "Keep-Alive": [
            "timeout=15, max=100"
        ],
        "Server": [
            "Apache/2.2.22 (Ubuntu) PHP/5.3.10-1ubuntu3.10 with Suhosin-Patch mod_ssl/2.2.22 OpenSSL/1.0.1"
        ],
        "Connection": [
            "Keep-Alive"
        ],
        "Vary": [
            "Accept-Encoding"
        ],
        "Date": [
            "Fri, 30 Jan 2015 13:00:33 GMT"
        ],
        "Content-Type": [
            "text/html"
        ],
        "X-Powered-By": [
            "PHP/5.3.10-1ubuntu3.10"
        ]
    }
}

Proxy examples

The following examples show how to configure Moogsoft Onprem Moobots when a proxy server is used for connection to Moogsoft.

You can define a proxy in the following ways:

proxy: "proxyuser:passw0rd@proxyhost:1223"

proxy: "proxyhost:1223"

proxy: {
        host: "proxyhost",
        port: 1223
        }
Situation Manager

The following example shows how to update the Situation Manager to send a REST.V2 updateSituation message through a proxy server.

  1. Edit the Situation Manager Moobot file, located at$MOOGSOFT_HOME/bots/moobots/SituationMgr.js.

  2. Modify theupdateSitnfunction to utilize the POST action. For example:

    function updateSitn(situation)
    {
            var sig_id = situation.value("sig_id");
            logger.warning("Update Situation Processed: " + sig_id);
        doPOST(sig_id);
    }
  3. Insert the proxy block into the POST action. For example:

    function doPOST(sig_id)
    {
            var request = REST.sendPost({
                    url:"http://surveilanceserver_84:9090/reportAntiSoc",
                    params: {
                            crime: "Graffiti"
                    },
            proxy: {
                host: "proxyserver",
                port : 3128,
                user : "username",
                encrypted_password:"zm0lxjTGiAhp6LrpM49+kr4SDtHj/fq16+i+hD1MG4c="
            },
                    callback: function(response, request)
                    {
                            if (response.success) {
                                    logger.warning("4764 CALLBACK SUCCESS ("+sig_id+") RESPONSE - ("+response.status_code +" - "+response.response+") REQUEST - "+ JSON.stringify(request));
                            } else {
                                    logger.warning("4764 CALLBACK FAILURE ("+sig_id+") RESPONSE - ("+response.status_code +" - "+response.response+" - "+response.status_msg+") REQUEST - 
                                    " + request.status_code + " " + request.response + " " + request.status_msg);
                            }
                    }
            });
            logger.warning("4764 POST REQUEST SENT FOR "+sig_id+" ...");
    }
ServiceNow

The following example demonstrates how to configure the ServiceNow ticketing integration when Moogsoft Onprem is installed on-prem and ServiceNow is in the cloud, and the two systems communicate through a proxy server.

  1. Edit the ServiceNow Moobot file, located at $MOOGSOFT_HOME/bots/moobots/ServiceNow-2.0-Geneva.js and define a variable containing the proxy details. For example:

    var proxy = {
      host: 'proxy-app.company.com',
      timeout:60,
      port: 8080
      }
  2. Add the proxy to the POST actions in the AddToWorkNotes and resolveIncident functions. For example:

    var rc = REST.sendPost({
      'url': url,
      'body': JSON.stringify(urlParameters),
      'user': user,
      'password': password,
      'content_type': "application/json",
      'proxy': proxy,
      'disable_certificate_validation': true
      });