How to download Attachments from RITM through Scripted REST API

abhinavnishant
Tera Contributor

I need to create a Scripted REST API which shall accept the RITM numbers and return the attachments associated with the given RITM.

This is my Sample Code:

------------------------------------------------------------------------------------------------------------------------------------------------------

(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
 
 var queryParams = request.queryParams;
 var queryRITM = queryParams.RITM;
 //queryRITM = queryRITM.split(',');
 
 var gr = new GlideRecord('sc_req_item');
 gr.addQuery('number',queryRITM);
 gr.query();
 while (gr.next()){
  
  var ga = new GlideRecord('sys_attachment');
  ga.addQuery('table_sys_id',gr.sys_id.toString());
  ga.query();
  while(ga.next()){
  var hdrs = {},
        attachment_sys_id = ga.sys_id;
    hdrs['Content-Type'] = "'"+ ga.content_type+ "'";
    response.setStatus(200);
    response.setHeaders(hdrs);
    var writer = response.getStreamWriter();
    var attachmentStream = new GlideSysAttachmentInputStream(attachment_sys_id);
    writer.writeStream(attachmentStream);
  }
  }
 })(request, response);
---------------------------------------------------------------------------------------------------------------------------------------------------------------
 
I am getting the download option in Postman, but the returned file has the name "response" without and extension.
Can I have the filename same as the filename in "sys_attachment" table?
 
What are the alternate ways to get the attachment from an RITM?
I did explored the Attachments API and I see I need to pass the sysID of the file. 
Is there a way I can use/reuse the Attachment API in Scripted REST API and get to download the related attachments?
Any help will be appreciated.
Thanks,
-Abhinav
10 REPLIES 10

Debarpita Basak
Giga Contributor

hi abhinavnishant,

can u please give the exact code which gave you exact download attachment output. Please.