Moogsoft Docs

REST.V2

Description

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

The REST.V2 MooBot

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

The REST.V2 MooBot module supports asynchronous operation (using Callback functions), to send a request without blocking the javascript code execution until the request is completed.

The REST.V2 MooBot module supports timeout (using the timeout property), to make the request fail after a specified time.

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

To use, at the top of a MooBot js file, define a new global object REST to load the REST.V2 module:

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

Reference Guide

REST.sendGet

REST.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

E.g. 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 Moog 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"

Note

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"
        ]
    }
}
REST.sendPost

REST.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

E.g. 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 Moog 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"

Note

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
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 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"
}
REST.sendPut

REST.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
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.

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"
        ]
    }
}

Note

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, if we wanted to send the entire alert custom_info object as part of a url-encoded body, we would do the following:


 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);
REST.sendDelete

REST.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
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.

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"
        ]
    }
}
REST.send

REST.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 Moog 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 Example

Proxy Example

As an example, you could modify the SituationMgr.js in order to send an updateSituation message via REST.V2 through a proxy server:

function updateSituation(situation)
{
	var sig_id = situation.value("sig_id");
	logger.warning("Update Situation Processed: " + sig_id);
    doPOST(sig_id);
}

insert the proxy block into the REST.sendPost({...}) function as below:

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+" ...");
}

Some alternative methods of using the proxy functionality are below:

1.) proxy: "proxyuser:passw0rd@proxyhost:1223"

2.) proxy: "proxyhost:1223"

3.) proxy: {
	host: "proxyhost",
	port: 1223
}