Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

Scripted Rest API to update incident with attachment

Prasant Kumar 1
Kilo Sage

Hi Experts,

Can anyone help me with the code of scripted rest API to add an attachment with request payload?

 

@Ankur Bawiskar @asifnoor 

Thanks & Regards

Prasant Kumar Sahu

1 ACCEPTED SOLUTION

Hi,

Sample JSON request:

{
  "incidentNumber": "INC000124",
  "fileName": "my file.txt",
  "contentType": "text/plain",
  "fileData": "my sample file"
}

Scripted REST API Script:

(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {

	var requestBody = request.body.dataString;
	var parser = new global.JSON();
	var parsedData = parser.decode(requestBody);
	var number = parsedData.incidentNumber;
	var fileName = parsedData.fileName;
	var fileContentType = parsedData.contentType;
	var fileData = parsedData.fileData;

	var rec = new GlideRecord('incident');
	rec.addQuery('number',number);
	rec.query();
	if(rec.next()){
		var sa = new GlideSysAttachment();
		sa.write(rec, fileName, fileContentType, fileData);
		var responseBody = {};
		responseBody.incNumber = number;
		responseBody.status = "Success";
		response.setBody(responseBody);
	}
	else{
		var responseBodyFailure = {};
		responseBodyFailure.status = "Failure";
		response.setBody(responseBodyFailure);
	}

})(request, response);

Regards
Ankur

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

View solution in original post

25 REPLIES 25

Hi Ankur,

Using your above script for attachements creation along with creation of incident , i have written the below code. But I am getting 500 internal error.  with the below error message.

{
  "error": {
    "message": "Script Evaluation Exception",
    "detail": "Can't find method com.glide.ui.SysAttachment.write(string,undefined,undefined,undefined). (sys_ws_operation.f5d38f17ffbfc210b9bff9337c4fd93d.operation_script; line 37)"
  },
  "status": "failure"
}

Can you help me sorting this issue: 

(function process( /*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
// Implement resource here

var requestBody = request.body.data;
var incidentGR = new GlideRecord('incident');
incidentGR.initialize();

// Set fields without inserting the record yet
incidentGR.short_description = requestBody.short_description;
incidentGR.description = requestBody.description;
incidentGR.u_store_id = 'kiko_store';
incidentGR.caller_id.setDisplayValue(requestBody.beneficiary);
incidentGR.category = requestBody.level1;
incidentGR.subcategory = requestBody.level2;
incidentGR.contact_type = 'Site Manager';
incidentGR.state = 1;
incidentGR.impact = 1;
incidentGR.urgency = 3;
incidentGR.assignment_group.setDisplayValue('XXXXX Support');
incidentGR.company.setDisplayValue('XXXXXX');

var incidentSysID = incidentGR.insert();

var attachmentIDs = [];
if (requestBody.attachments && requestBody.attachments.length > 0) {
for (var i = 0; i < requestBody.attachments.length; i++) {
var attachment = requestBody.attachments[i];

var parser = new global.JSON();
var parsedData = parser.decode(attachment.data);
var fileName = parsedData.fileName;
var fileContentType = parsedData.contentType;
var fileData = parsedData.content;

if (incidentSysID) {
var sa = new GlideSysAttachment();
var attachmentSysID = sa.write(incidentSysID, fileName, fileContentType, fileData);
attachmentIDs.push(attachmentSysID);
}
}
}

// Return response with incident and attachment info
response.setBody({
sys_id: incidentSysID,
number: incidentGR.number,
caller_id: incidentGR.caller_id.getDisplayValue(),
short_description: incidentGR.short_description,
description: incidentGR.description,
contact_type: incidentGR.contact_type,
company: incidentGR.company.getDisplayValue(),
state: incidentGR.state,
priority: incidentGR.priority,
assignment_group: incidentGR.assignment_group.getDisplayValue(),
category: incidentGR.category,
level1: incidentGR.category,
level2: incidentGR.subcategory,
attachments: attachmentIDs
});
 
})(request, response);
********************************************************************************
My Request Body is as below: 
"beneficiary": "73A",
"short_description": "Issue with mobile device",
"description": "Issue with mobile device",
"level1": "iphone",
"level2": "Charging",
"attachments": [
{
"fileName": "example.txt",
"contentType": "text/plain",
"content": "VGhpcyBpcyBhIHNhbXBsZSBmaWxlIGNvbnRlbnQu"
}
]
}
 

Hi Ankur,

 

I have similar requirement where I need to create an incident and attach the file while creating and also the attachment is muti form such as image and othe types of files, I tried various scripts but multi form is not working. can you help me in this. 

 

Thanks in advance.

Hi Naveen,

If you are writing a scripted Rest API , it will be useful. I could attach  all media, vedios/images/text files.  Please give thumbs up if it works for you.

 

var incidentSysID = incidentGR.insert();

if (incidentSysID) {
// Handle attachments if any
var attachmentIDs = [];
if (requestBody.attachments && requestBody.attachments.length > 0) {
var attachment = new GlideSysAttachment();
for (var i = 0; i < requestBody.attachments.length; i++) {
var attachmentData = requestBody.attachments[i];
var fileName = attachmentData.fileName;
var contentType = attachmentData.contentType;
var content = attachmentData.content;
var base64EncodedContent = attachmentData.content;
var regularContent;
if (contentType === 'text/plain') {
regularContent = GlideStringUtil.base64Decode(base64EncodedContent);
} else if ((contentType === 'image/jpeg') || (contentType === 'image/png') || (contentType === 'image/jpg') || (contentType === 'video/mp4')) {
regularContent = GlideStringUtil.base64DecodeAsBytes(base64EncodedContent);

}
// Write attachment
var attachmentSysID = attachment.write(incidentGR, fileName, contentType, regularContent);
attachmentIDs.push({
file_name: fileName,
content_type: contentType,
file_sys_id: attachmentSysID,
content: content
});
gs.info('The attachment sys_id is: ' + attachmentSysID);
}
}

// Return response with incident and attachment info
response.setBody({
//number: incidentSysID,
number: incidentGR.number,
"record": {
short_description: incidentGR.short_description,
company: incidentGR.company.getDisplayValue(),
description: incidentGR.description,
contact_type: incidentGR.contact_type,
state: incidentGR.state,
priority: incidentGR.priority,
assignment_group: incidentGR.assignment_group.getDisplayValue(),
caller_id: incidentGR.caller_id.getDisplayValue(),
category: incidentGR.u_storecode,
level1: incidentGR.category,
level2: incidentGR.subcategory,
attachments: attachmentIDs // Include all attachment details
}
});
} else {
// Handle the case where the incident could not be inserted
response.setStatus(500);
response.setBody({
error: 'Failed to create incident'
});
}

 

asifnoor
Kilo Patron

Hi Prashant.

Check out this link. It has good information with examples.

https://docs.servicenow.com/bundle/paris-application-development/page/integrate/custom-web-services/...

Secondly, you can use REST API Explorer and build an request there. Then once done, in that page you can click on ServiceNow Script which gives you complete script to update the incident.

Mark the comment as a correct answer and also helpful once worked.

Hello Prashant,

If this has answered your question, kindly mark the comment as a correct answer so that the question is moved to the solved list and others looking for similar solution can be benefitted from it.