Getting attachments in ServiceNow

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.

Categories:ServiceNow, TIL

Tagged as: , , , ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s