Getting attachments in ServiceNow

Sumeet Sumeet Follow Jul 17, 2020 · 1 min read
Getting attachments in ServiceNow
Share this

One of my friends got in touch with me to ask how do we fetch the attachments from an REST endpoint and store it within ServiceNow? I basically did not have a ready answer to this which piqued my curiosity. This is rather an essential functionality and I was sure there exists some straightforward solution to this. Blaming my ignorance, I continued to search for the right API and without any surprise I found it.

It is part of RESTMessageV2 class and the function name is saveResponseBodyAsAttachment. Below is a simple implementation to make this work. I created a REST Message by name ‘FetchImageAPI’ and I used a generic public image url as an endpoint in this message. Before .execute()ing this request, you need to instruct the request object to save response body as attachment using .saveResponseBodyAsAttachment() function. In order to do so you need to specify:

  1. On which record do you have to attach the image? a. First parameter: table name   b. Second parameter: sys_id of the record on that table
  2. What should be the name of the attachment?   a. Third parameter: name of the attachment along with extension

This is because you cannot just upload the attachment randomly in ServiceNow. Attachment should always be associated with a record.

var r = new sn_ws.RESTMessageV2('FetchImageAPI', 'Default GET');
r.saveResponseBodyAsAttachment(<table name>, <record sys_id>, <name of image>);
var response = r.execute();
var responseBody = response.getBody();
var httpStatus = response.getStatusCode();

Link to RESTMessageV2 documentation.

I have been working with ServiceNow for a long time now and it is the majority part of my career today. Also thankful to ServiceNow for recognising me as Developer MVP for 2020.

Join Newsletter
Get the latest news right in your inbox!
Written by Sumeet Follow
Hi, I am Sumeet, and I believe the world belongs to the doers. Here, I publish my technical tinkering experiences. I hope you like it!