Make API Calls from a SNIPPET Action

You can make REST or SOAP API calls from a SNIPPET action. This is one of the supported methods of making API calls in Studio scripts.

This is not the recommended method for making REST calls because it has the potential to slow down contact handling and cause serious performance issues with the platform. Use one of these preferred methods instead: 

  • Integration Hub: This is the most secure option and ensures that your client credentials are not stored in plain text.
  • REST API Action: Using the REST API action is the recommended alternative if you are not using Integration Hub.

However, if you're connecting to a SOAP web service or if your API calls include XML, making calls from SNIPPET is the method you must use. If you must use SNIPPET, review the recommendations for how to more safely make these API calls.

In addition to seeing HTTP status codes in responses, you may see a -1 code. This is an internal code that indicates an error has occurred with the response.

Caution

Building API calls within a snippet is not recommended. It may lead to serious performance issues that impact contact handling and negatively impact your tenant. For a more secure and reliable experience, use one of the following preferred methods.

There are two cases where making calls from SNIPPET is the method you must use: if you're connecting to a SOAP web service or if your API calls include XML. If you must use SNIPPET for API calls: 

  • Limit timeouts in your API calls. A general recommendation is that timeouts be no more than two seconds. The default timeouts may be longer, so always verify the timeouts to ensure that they do not exceed this maximum. If you find that longer timeouts are required, adjust your web service if possible to improve its response times.
  • Be extremely careful with loop logic. The combination of loops and long timeouts compound the potential impact on your system.
  • The maximum response size in NiCE CXone is 32 KB. The limit is strictly enforced to prevent cluster instability and outages. Studio enforces this limit when saving the script, but Desktop Studio does not. If you can, use the REST API actionaction or Integration Hub instead of the SNIPPET action to make API calls. They have the same limit, but can handle a heavier load. If you must use the SNIPPET action, follow these tips to reduce the size of the returned data: 

    • Filter the data in the API response: For example, if you're using the NiCE reporting API to get contacts, you can filter the results by the startDate and endDate of the contact. This API call also allows you to return and limit a top count of items. Refer to the API documentation that came with your script integration to determine what filtering you can use.

    • Update the API request to return only the data you need: For example, if you're using the NiCE reporting API to get contacts, you can use the contactId or agentId fields to return only relevant data. Refer to the API documentation that came with your script integration to determine what data limits you can use.

    • Build middleware: If you cannot do either of the previous options, build middleware that does filtering based on custom criteria you define. If you do this, ensure that your middleware does not add latency to the call.

Connect to RESTful Web Services with a SNIPPET Action

 

You can use Studio scripts to connect with RESTful APIs using the REST proxy in a Snippet action. You can access this service with the GetRestProxy() function. The REST proxy allows your scripts to interact with remote web servers. It provides some properties and functions that you can use to do this. The properties and functions are described later in this section. The NiCE CXoneplatform lets REST APIs return up to 32 KB of data. This limitation is imposed at the platform level and is strictly enforced.

The REST proxy requires the use of dynamic data objects. The dynamic data type allows your scripts to work with responses formatted in XML and JSON. Dynamic data objects can receive data in these formats and allow it to be read. You can also dynamically create objects that can be converted into either XML or JSON. These abilities are necessary when using RESTful APIs.

To use the REST proxy, add a Snippet action to your script and open the Snippet editor window. Call the GetRESTProxy() function using the following syntax:

ASSIGN proxy = GetRESTProxy() 
 proxy.<property | function>([parameters]) 

For <property | function>, choose from the properties and functions described in the following sections.

Properties

Property Details
StatusCode

Holds the HTTP status code following a call to MakeRestRequest(). This property cannot be modified. If the function fails, it no longer holds the status code.

StatusDescription Holds the HTTP status description following a call to MakeRestRequest(). This property cannot be modified.
ContentType

Allows you to override the default content-type header. The default is application/x-www-form-urlencoded.

Depending on the call you're making, you may need to change the header. For example, if you're sending JSON, you should change this to application/json. You must modify this property.

ProxyTimeoutSeconds Allows you to change the request timeout. The default is 10 seconds. You must modify this property.

Functions

The following table provides information about the functions available for use when connecting to RESTful APIs. There are additional REST proxy functions that allow you to encode and hash strings.

Function Details
MakeRestRequest(p1, p2, p3, p4)

Performs an HTTP request to the designated URL, where: 

  • P1: URL of the request; String
  • P2: Payload for the API call; String
  • P3: Accept header and response parser selector; Numeric or String:
    • 0:  application/json
    • 1: text/xml
    • 2: application/json (ignore response body)
    • 3: text/xml (ignore response body)
      • "JSON" - application/json
      • "XML - text/xml
  • P4: REST API verb; String
AddHeader Adds a custom header to the HTTP request.
ClearHeaders Clears any custom headers added with AddHeader.
currentUnixTimestamp()

Returns the current time as a Unix timestamp. Only for use with getRESTProxy(). Learn more about this function on the Built-In Functions help page.

Examples

ASSIGN proxy = GetRESTProxy()
ASSIGN proxy.ContentType = "application/json"
ASSIGN url = "https://catfact.ninja/fact"
ASSIGN verb = "GET"
ASSIGN result = proxy.MakeRestRequest(url,payload,'JSON',verb)

 

ASSIGN restProxy=GetRESTProxy()

restProxy.AddHeader("x-api-key", "qwer") //Assigning incorrect header for demonstration purposes
restProxy.ClearHeaders()
restProxy.AddHeader("x-api-key", "asdf")
ASSIGN restProxy.ProxyTimeoutSeconds = "2"
ASSIGN restProxy.ContentType = "application/json"

ASSIGN uri = "http://postman-echo.com/post"

DYNAMIC beowulfCharacteristics
ASSIGN beowulfCharacteristics.name = "Beowulf"
ASSIGN beowulfCharacteristics.occupation= "Hero" 
ASSIGN beowulfCharacteristics.foe = "Grendel"
ASSIGN payloadJSON = "{beowulfCharacteristics.asJSON()}"

Connect to SOAP Web Services with a SNIPPET Action

You can use SOAP-based web services with Studio scripts. This requires that you import a WSDL or Proxy DLL into Studio. The imported DLL must be authorized by NiCE CXone. After authorizing the DLL, it's saved in the root of your NiCE CXone system's file storage.

Using SOAP web services requires assistance from NiCE CXone. Contact your account representative for more information.

When you want to use a SOAP-based web service in a Studio script, you must create a snippet. Add a Snippet action to your script. In the Snippet editor window, add a USES statement that names the proxy DLL file that you generated and stored in your business unit's file storage.

The following snippet is an example of using a SOAP-based web service with a Studio script:

USES "sf.dll"
cStart="{now}"
sforce=new SforceService()
session=new SessionHeader()
loginResult=sforce.login("demo@nice.com",password6")
sforce.sessionheadervalue=session
session.sessionid=loginResult.sessionid
sforce.url=loginresult.serverUrl

t=new Task()
t.ActivityDate=#"8/20/2050"
t.Description="Call placed by {first }{Last}."
t.Subject="Call @{cStart}"
t.Status="Completed"
t.CallType="Outbound"
t.OwnerId=SF_Agent_ID
t.ReminderDateTime="{cStart}"

SWITCH Type
{
   CASE "CON" { t.WhoId=SF_Obj_ID }
   CASE "LEA" { t.WhoId=SF_Obj_ID }
   CASE "ACC" { t.WhatId=SF_Obj_ID }
   CASE "OPP" { t.WhatId=SF_Obj_ID }
   CASE "CAS" { t.WhatId=SF_Obj_ID }
}
SaveResult=sforce.create(t)
	

Make a SOAP Call with a REST Wrapper

This option allows you to use REST API methodologies to make call SOAP-based web services. Every web service responds differently depending on how it's built. You may need to modify the example code to work with the service you're calling.

The XML you use cannot include double quotes when you use it in a SNIPPET action. You can use either of the following alternatives: 

  • Replace each double quote with {char(34)}, which inserts a double quote character directly into the string. This option is illustrated in the first example in step two later in this section.
  • Replace each double quote with a single quote ( ' ). This is acceptable in XML and in SNIPPET actions. This option is illustrated in the second example in step two later in this section.

You only need to replace double quotes that appear in the XML. Variable assignments in the snippet code must still be enclosed in double quotes.

  1. Make a REST proxy, assign the ContentType header as the web service you're connecting to requires it, and the public web service URL:

    ASSIGN RestProxy = GetRESTProxy() 
    ASSIGN RestProxy.ContentType = "text/xml; charset=utf-8"
    ASSIGN URL = "https://localhost:9031/ssodir/services/

    SSODirectoryService" //Assign the public Webservice UR
  2. Create your SOAP envelope, which is XML formatted to encode all the required parameters. You can do this in two ways: 

    • Separate each line. This option is easier to read.

    • Concatenate everything in a single line.  

    Examples of both options are included in this step.

    This example shows the envelope separated into lines. Additionally, this example shows double quotes replaced with {char(34)}.

    //Sample Payload:
    ASSIGN Payload = ""
    ASSIGN Payload = "{Payload}<?xml version={char(34)}1.0{char(34)} encoding={char(34)}UTF-8{char(34)}?>"
    ASSIGN Payload = "{Payload}<soapenv:Envelope"
    ASSIGN Payload = "{Payload} xmlns:soapenv={char(34)}http://schemas.xmlsoap.org/soap/envelope/{char(34)}"
    ASSIGN Payload = "{Payload} xmlns:xsd={char(34)}http://www.w3.org/2001/XMLSchema{char(34)}"
    ASSIGN Payload = "{Payload} xmlns:xsi={char(34)}http://www.w3.org/2001/XMLSchema-instance{char(34)}>"
    ASSIGN Payload = "{Payload}<soapenv:Body>"
    ASSIGN Payload = "{Payload}<ns1:getIDPList"
    ASSIGN Payload = "{Payload} soapenv:encodingStyle="
    ASSIGN Payload = "{Payload} {char(34)}http://schemas.xmlsoap.org/soap/encoding/{char(34)} "
    ASSIGN Payload = "{Payload}xmlns:ns1="
    ASSIGN Payload = "{Payload} {char(34)}https://localhost:9031/ssodir/services/"
    ASSIGN Payload = "{Payload}  SSODirectoryService{char(34)}/>"
    ASSIGN Payload = "{Payload}</soapenv:Body>"
    ASSIGN Payload = "{Payload}</soapenv:Envelope>"

    The following example shows the envelope code concatenated in one line. In this example, the double quotes have been replaced with single quotes.

    //Sample Payload:
    ASSIGN Payload = "<?xml version='1.0' encoding='UTF-8'?><soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><soapenv:Body><ns1:getIDPList soapenv:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/' xmlns:ns1='https://localhost:9031/ssodir/services/SSODirectoryService'/> </soapenv:Body></soapenv:Envelope>"
    
  3. Execute the REST request. The following example is being executed as a POST.

    Result = RestProxy.MakeRestRequest(URL,Payload,1,"POST")