Note: API plugins must be implemented in Python and the following code samples are based on Python 3.1.

This plugin defines a class API Plugin and must meet the following requirements:

Class Parameter

Value

Explanation

Class Name

APIPlugin

Case-sensitive.

Member Function

_init__(self, user, pwd, url)

When you create an instance of API plugin, NetBrain API framework will invoke this function and set the parameters to be the ones defined in the API server for a tenant.

The instantiation operation must have four parameters:

the object itself

username

password

the endpoint of the server

 
This is the sample code for this function:

def __init__(self, user, pwd, url):
        self._usr = user
        self._pwd = pwd
        self._urlprefix = '/'.join([url, 'api/now/table'])

Here the instance variables _usr, _pwd and _urlprefix are set according to the inputs when you define an API server. The endpoint of ServiceNow API call is https://<ServiceNowUrl>/api/now/table, so you can join ServiceNow URL with /api/now/table.

Member Function

_test(self)

This function is used to debug the plugin function.
It does not have any parameters except the API server object itself.

 
Now you can define the member functions to retrieve the data from the API server. The definition includes the following two parts:

Definition

Explanation

Multi-line comments (mandatory)

It works as protocols between NetBrain system and APIPlugin class.

NetBrain API framework will parse these comments, and then pass the corresponding method and variables to other components of NetBrain system, such as Search function.

Example: Multi-line comments for a member function getAlertsByDev(self, params)

'''
    <function>
        <name>getAlertsByDev</name>
        <desc>Get alerts Info by device name</desc>
        <input>
            <var name="deviceId" type="string" />
            <var name="deviceName" type="string" />
        </input>
        <output>
            <var name="NumberOfAlerts" type="string" />
            <var name="Alerts" type="table">
                <var name="Severity" type="string" />
                <var name="Short_Description" type="string" />
            </var>
        </output>
    </function>
    '''
def getAlertsByDev(self, params):

The comments are quoted by delimiter (’’’) and are in XML format. The comments include the following parameters:

namemandatory and must be exactly the same as the function name.

descoptional description.

inputmandatory and corresponds to the key values of input parameters params, which is a dictionary. It should always include deviceID and deviceName, indicating that the function returns the data for this device. It can also include interfacename, indicating that the function returns the data for this specific interface of this device.

outputmandatory and defines what data is returned. The function always returns the data as a dictionary. In this sample, the returned dictionary has two keys NumberOfAlerts and Alerts which is a dictionary with two keys Severity and Short_Description. The implementation of the function must return a dictionary which includes the key and values defined in these comments.

Python codes to implement the function

The function retrieves the data from third-party API servers. The implementation is based on API calls of third-party systems and can be different. However, if the third-party system supports RESTful API, the codes are similar and usually include three major steps:

1.Set Proper Request Parameters.

2.Make an API Call.

3.Parse the Response.

 

Setting Proper Request Parameters

ServiceNow offers a friendly API Browser for you to browse and test its API calls.

1.Log into a ServiceNow instance and navigate to REST API Browser (search for Rest API to find the link to API browser).

 
In this case, Table API will be used to retrieve records from a table with the URL https://{ServiceNow InstanceURL}/api/now/table/{tableName}. The table name for Alert records is em_alert and so the full URL to get records for alerts from ServiceNow will be https://{ServiceNow InstanceURL}/api/now/table/em_alert.

2.Set the query parameters for this table. To make the sample code simple, you can keep the most parameters as default and select sysparm_fields as short_description, severity, node and add an additional parameter node as the device name.

Note: The node field is mandatory for an alert and assumed to be the device name.

Example: A response from ServiceNow.

3.Put these together in Python codes:

# Set the request parameters.
  #URL for Table API: urlprefix is  https://<ServiceNowUrl>/api/now/table
          url_table = '/'.join([self._urlprefix, 'em_alert'])
 
        #query parameters
        deviceName = params['deviceName']
        urlparams = {
            "sysparm_fields":"short_description,severity,node",
            "node":deviceName}
 
                                     # Set proper headers
        headers = {"Content-Type""application/json",
                    "Accept""application/json"}
                    
        #authentication 
        auth =(self._usr, self._pwd)

The last two paragraphs set the headers and authentication of the request.

These two request headers must have one of the following valid values and require proper data formatting. Here we use the JSON format.

oContent-Typeapplication/json, application/xml

oAcceptapplication/json, application/xml

For authentication, ServiceNow supports the basic authentication (the credentials are sent for each HTTP request) and OAuth (authentication will be performed in advance and a unique token will be generated which can be used in HTTP requests). Here we use the basic authentication.

In addition, you can set a version number, like /api/now/v1/table/{tablename}. By specifying a version number in the URL, you can ensure that any future updates to the REST API will not negatively impact your integration. URLs that do not specify a version number will use the most recent REST API behavior available with your instance version, which may change as soon as you upgrade. In the sample, we do not set API version in the URL.

Making an API call

Making an API call is easy with the help of Python Request library. See http://docs.python-requests.org/en/master/ for more details.

response = requests.get(url_table, auth = auth, headers=headers, params = urlparams)
        if response.status_code != 200:
            return []

After the Get class, the codes check whether the API call is successful (200 indicates a success). If not, an empty dictionary will be returned.

Building Dictionary from API Response

The result is in the JSON format as specified in the request headers. You need to loop through the result and build the dictionary as defined in the multi-line comments of this function. The key words of the returned dictionary must be identical to those defined in the comments.

result = response.json().get('result')
        alerts = []
        for i in result :
            alerts.append({'Severity' : i['severity'],
                              'Short_Description' : i['short_description'],
                              })
        
        return {'NumberOfAlerts' : len(result),
            'Alerts' : alerts}

After finishing this function, you can modify the _test function as follows to debug it:

def _test(self):
        paras = {"deviceName""BIGIP1"}
        alerts = self.getAlertsByDev(paras)
        return alerts

The _test function should always return an object type of dictionary. If the function call succeeds, the returned value will be printed out. Otherwise, the error message (with the call stack) will be displayed in the Testing dialog.

Note: Python print statements will not be displayed.