How to retrieve Binary PDF file from REST API File response.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
06-09-2025 12:50 PM
Hi Everyone,
I am calling a third-party API that returns a PDF file in the response. I need to attach this binary PDF file to a RITM record. Below is my code — it creates the attachment, but the file content is not being added correctly.
(function execute(inputs, outputs) {
var caseNumber = inputs.casenumber;
var language = 'english'; // Default language
var endPoint = gs.getProperty('baseURL') + '/case/' + caseNumber + '/notice?language=' + language;
try {
var request = new sn_ws.RESTMessageV2();
request.setHttpMethod('GET');
request.setEndpoint(endPoint);
request.setRequestHeader('Accept', 'application/pdf');
request.setRequestHeader('Authorization', 'Bearer ' + inputs.access_token);
var response = request.execute();
var httpResponseStatus = response.getStatusCode();
if (httpResponseStatus === 200) {
var inputStream = response.getBinaryResponseStream();
var gr = new GlideRecord('sc_req_item');
if (gr.get(inputs.requested_item)) {
var attachment = new GlideSysAttachment();
var attachmentSysId = attachment.write(gr, 'Further_Action_Notice.pdf', 'application/pdf', inputStream);
if (attachmentSysId) {
gs.info(':white_check_mark: FAN PDF attached successfully to RITM: ' + gr.number);
outputs.response = 'PDF attached successfully';
} else {
gs.error(':x: Failed to write PDF attachment');
outputs.response = 'Attachment write failed';
}
} else {
gs.error(':x: Requested item not found: ' + inputs.requested_item);
outputs.response = 'Requested item not found';
}
} else {
gs.error(':x: PDF fetch failed. Status: ' + httpResponseStatus + ', Body: ' + response.getBody());
outputs.response = 'Failed to retrieve PDF. Status: ' + httpResponseStatus;
}
} catch (ex) {
gs.error(':x: Exception occurred: ' + ex.getMessage());
outputs.response = 'Exception: ' + ex.getMessage();
}
})(inputs, outputs);

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
06-10-2025 02:37 AM
Hi,
Check whether the script shared in this thread is useful. Use the base64EncodedData to GlideAttachment and see whether PDF is created properly
Palani
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
06-10-2025 02:47 AM
the write method takes content, but you are possibly getting content stream
check this link
Attachment API GET Convert Binary String to File Attachment
Also check and try to use writeContentStream() method
If my response helped please mark it correct and close the thread so that it benefits future readers.
Ankur
✨ Certified Technical Architect || ✨ 9x ServiceNow MVP || ✨ ServiceNow Community Leader