Sending Attachment using Rest API

ramesh_r
Mega Sage

Hi

 

I want to send attachment using rest api for that i have created BR on the incident table and written the below script but its not working can anyone please correct this script

 

var target = new GlideRecord('sys_attachment');
target.addQuery('table_name', 'incident');
target.addQuery('table_sys_id', current.sys_id);
target.query();

while(target.next()) {
var t = target.content_type;
var sa = new GlideSysAttachment();
var binData = sa.getBytes(target);
var base64Data = GlideStringUtil.base64Encode(binData);

var s ="https://dev61883.service-now.com/api/now/attachment/file?table_name=incident&table_sys_id=82c3b785dbd7a300a8890d53ca9619ac&file_name="+target.file_name;

var body= {
"name":t,
"source":"incident:38a83c61db132300a8890d53ca96194d",
"payload":base64Data
};
//Send Attachments
var requestAttachment = new sn_ws.RESTMessageV2();
requestAttachment.setEndpoint(s);
requestAttachment.setHttpMethod('POST');
requestAttachment.setBasicAuth('admin','adminadmin');
requestAttachment.setRequestHeader("Accept","application/json, text/plain, */*");
requestAttachment.setRequestHeader('Content-Type','application/json');
requestAttachment.setRequestBody(body);
var response = requestAttachment.execute();
gs.addErrorMessage(response.getBody());

}

 

1 ACCEPTED SOLUTION

josh_nerius
ServiceNow Employee
ServiceNow Employee

Hi Ramesh, 

The Attachment API at /now/attachment/file expects a binary payload. Base64 won't work in this case. 

There's an easy fix. RESTMessageV2 has a method called setRequestBodyFromAttachment(attachmentSysId). Use this instead of setRequestBody. You can remove all of the code that calls GlideSysAttachment and just pass the Sys ID of the attachment to this method. 

View solution in original post

14 REPLIES 14

josh_nerius
ServiceNow Employee
ServiceNow Employee

Hi Ramesh, 

The Attachment API at /now/attachment/file expects a binary payload. Base64 won't work in this case. 

There's an easy fix. RESTMessageV2 has a method called setRequestBodyFromAttachment(attachmentSysId). Use this instead of setRequestBody. You can remove all of the code that calls GlideSysAttachment and just pass the Sys ID of the attachment to this method. 

Which business rule has been used here?

That worked amazingly, once I realized I also needed to get the content-type from the attachment and set it in the header for the REST call.  Thank you for posting this.

Aoife Lucas (they/them)

Does this function send the attachment in Base64 format?