Writing a custom script - V1 API
You will need a working knowledge of:
- JavaScript Object Notation (JSON)
- Python
A custom action script file is generally structured as follows:
- Import required packages
- Get input arguments
- Implement the logic
- Return JSON
Import required packages
Listed below are the most frequently used packages along with their usage:
Package Usage
Sys Fetches the input arguments
json Manipulates JSON data
requests Makes API calls
datetime Transforms time from millisec to the required date format
Get input arguments
The arguments for the script file can be fetched using sys.argv[index] where index starts from 1 to number of arguments passed.
When the argument passed is $COMPLETE_JSON_FILE (the path to the file containing the request JSON), the JSON file can be read using the following snippet:
file_Path = sys.argv[1]
with open(file_Path) as data_file:
data = json.load(data_file)
Implement the logic
The following snippet is for making an API call:
with requests.Session() as s:
url = 'api_url'
r = s.post(url,verify=True, data=post_data,headers=headers)
Construct the api_url, post_data and headers as required.
The following snippet is to transform time from millisec to required date format:
date = datetime.datetime.fromtimestamp(int(millisec)/1e3).strftime('%d %b %Y, %H:%M:%S')
Construct return JSON
A sample JSON such as {"key":"value"} can be constructed a follows:
json = {}
json["key"] = "value"
print(json)
A sample JSON array such as [{"key":"value"}] can be constructed a follows:
json = {}
json["key"] = "value"
result = []
result.append(json)
print(result)
Some operations can be performed using the JSON returned from the script. Learn about the operations performed using return JSON here.
Following is an example that shows the construction of a JSON that updates a request's additional fields JIRA_ISSUE_ID & JIRA_ISSUE_URL and adds a note about it.
jiraissueid = responseobj['id']
jiraissueurl = responseobj['self']
updateReqArray={}
updateReqArray['JIRA_ISSUE_ID']=jiraissueid
updateReqArray['JIRA_ISSUE_URL']=jiraissueurl
updateFieldsJson={"INPUT_DATA":[]}
updateFieldsJson['INPUT_DATA'].append(updateReqArray)
updateFieldsJson["OPERATIONNAME"]="EDIT_REQUEST"
note={}
note["notestext"] = "Jira Request Created with ID: "+jiraissueid+"</br> Issue Link: "+jiraissueurl
noteObject={}
noteObject["notes"]=note
addNoteJson={}
addNoteJson['INPUT_DATA']=[]
addNoteJson['INPUT_DATA'].append(noteObject)
addNoteJson["OPERATIONNAME"]="ADD_NOTE"
resultjson={}
resultjson["result"] = "success"
resultjson["message"] = "A Jira Request has been Created. Note with the Issue ID and URL has been added."
resultjson["operation"] = []
resultjson["operation"].append(updateFieldsJson)
resultjson["operation"].append(addNoteJson)
#Returning the JSON
print(resultjson)
Input Parameters
Request parameters and all API parameters can be passed as arguments to script files. Note that arguments cannot be passed to class files.
The following table lists the supported arguments.
Parameter Returns Request Property
$WORKORDERID Request ID
$REQUESTER Name of the requester
$CREATEDBY Name of the technician who created the ticket on requester's behalf
$CREATEDTIME Time at which the request was created (Millisec)
$DUEBYTIME Due by time (Millisec)
$RESPONSEDUEBYTIME Response due by time (Millisec)
$RESPONDEDTIME Time at which the request was responded to (Millisec)
$RESOLVEDTIME Time at which the request was resolved (Millisec)
$COMPLETEDTIME Time at which the request was closed (Millisec)
$SHORTDESCRIPTION Shortened description
$TIMESPENTONREQ Time spent on request (Hours and minutes)
$SUBJECT Subject
$REQUESTTEMPLATE Request template using which the corresponding request was created (String)
$MODE Mode (String)
$SLA Service Level Agreement (String)
$ASSET Asset (String)
$DEPARTMENT Department (String)
$EDITORID The user ID of the Editor of the Service Request (Long)
$EDITING_STATUS The editing status of the Service Request (Long)
$IS_CATALOG_TEMPLATE Denotes whether the request is created using service catalog or incident catalog (Boolean)
$SITE Site (String)
$ISVIPUSER Indicates whether the user is a VIP or not (Yes or no)
$SERVICE Service category (String)
$CATEGORY Category (String)
$SUBCATEGORY Subcategory (String)
$ITEM Item (String)
$TECHNICIAN Name of the Technician assigned
$TECHNICIAN_LOGINNAME Login name of the logged in technician
$STATUS Status (String)
$PRIORITY Priority (String)
$LEVEL Level (String)
$IMPACT Impact (String)
$URGENCY Urgency (String)
$IMPACTDETAILS Impact Details
$REQUESTTYPE Type of the Request
$APPROVAL_STATUS The Approval status of the request (String)
$CLOSURECODE Reason for closing a request (String)
$CLOSURECOMMENTS Explanation for closing the request
$FCR First Call Resolution (Boolean)
$YETTOREPLYCOUNT A count of the number of replies to which the technician has not yet replied
$GROUP Group (String)
$DESCRIPTION Full description
$LOGIN_NAME Login name through which the request was raised
$LOGGEDIN_USER_NAME Display name of the user who raised the request
Other supported parameters
$DIFF_JSON ---> When a request is updated, the difference in the previous data and updated data will be passed as JSON string.
$COMPLETE_JSON_FILE ---> Complete request object and the difference object will be saved to a JSON file and the file path will be passed as string. E.g. (SDP_Home\integration\custom_scripts\request\12_1426143538036.JSON).
$COMPLETE_JSON structure
{
"request": {
"WORKORDERID": "17",
"REQUESTER": "Annie",
"CREATEDBY": "Heather Graham",
"CREATEDTIME": "1477984359352",
"DUEBYTIME": "1477991559352",
"RESPONSEDUEBYTIME": "1477991559052",
"RESPONDEDTIME": "0",
"RESOLVEDTIME": "0",
"COMPLETEDTIME": "0",
"SHORTDESCRIPTION": "Please create a user account for the new joinee and provide the requested resources.",
"TIMESPENTONREQ": "0hrs 0min",
"SUBJECT": "New hire request form",
"REQUESTTEMPLATE": "New Hire",
"MODE": "Web Form",
"SLA": "Medium SLA",
"ASSET": "iPhone 6 - PO# Apple_iPhone_43[52], MacBook Pro",
"IS_CATALOG_TEMPLATE": "false",
"SITE": "Zoho Corp - Chennai",
"ISVIPUSER": "No",
"SERVICE": "User Management",
"CATEGORY": "User Administration",
"TECHNICIAN": "Shawn Adams",
"TECHNICIAN_LOGINNAME": "shawn.adams",
"STATUS": "Open",
"PRIORITY": "Medium",
"LEVEL": "Tier 1",
"IMPACT": "Medium",
"URGENCY": "Normal",
"REQUESTTYPE": "New Joinee Request",
"FCR": "false",
"INTERESTEDPARTY": "hradmin1@org.com,hradmin2@org.com",
"GROUP": "HR group",
"DESCRIPTION": "Please create a user account for the new joinee and provide the requested resources.",
"Languages Known": [
"Java",
"Python",
"SQL"
],
"Job Type": "Software Developer Engineer",
"Qualification": "B. Tech Computer Science",
"Address": "My Door No : xx,\r\nMy street name,\r\nCity I live in.\r\nPostal code",
"Expected DOJ": "15 Nov 2016, 08:00:00",
"New Joinee Name": "John William",
"Years of Experience": "2.0",
"LOGIN_NAME": "heather.graham",
"LOGGEDIN_USER_NAME": "Heather Graham"
}
}
$DIFF_JSON structure
{
"diff": {
"DUEBYTIME": {
"OLD": "1476961659524",
"NEW": "1476940059524"
},
"MODE": {
"OLD": "E-Mail",
"NEW": "Phone Call"
},
"SLA": {
"OLD": "Low SLA",
"NEW": "Medium SLA"
},
"SERVICE": {
"OLD": "",
"NEW": "Data Management"
},
"CATEGORY": {
"OLD": "Desktop Hardware",
"NEW": "General"
},
"TECHNICIAN": {
"OLD": "Howard Stern",
"NEW": "Jeniffer Doe"
},
"PRIORITY": {
"OLD": "Low",
"NEW": "Medium"
},
"LEVEL": {
"OLD": "",
"NEW": "Tier 2"
},
"IMPACT": {
"OLD": "Low",
"NEW": "Medium"
},
"URGENCY": {
"OLD": "Low",
"NEW": "Normal"
},
"REQUESTTYPE": {
"OLD": "Incident",
"NEW": "Request For Information"
},
"GROUP": {
"OLD": "Network",
"NEW": "Printer Problems"
}
}
}
Whenever a request is edited, the DIFF_JSON is produced which can be used to devise workflows based on fields changes.
$COMPLETE_JSON_FILE
$COMPLETE_JSON_FILE denotes the file path of the file that has both the $COMPLETE_JSON and $DIFF_JSON together in a single JSON. Instead of passing too many parameters to the class/script, the file path can be passed and the script can open the file and access the required values.
The file is created temporarily and is deleted after the script is executed.
The temporary JSON file is created in SDP_Home\integration\custom_scripts\request\ directory, file name being <requestid_timestamp>.json.