How to send attachment from one servicenow to another?

SandeepKSingh
Kilo Sage

Hi Team,

I have one requirnment to share an Incident details created on one servicenow instance that should create on another servicenow instance.


Any sample code ??

 

 

Thanks

Snow Learner

3 ACCEPTED SOLUTIONS

Ravi Gaurav
Giga Sage

Hi,

you can use Business Rule (async BR on Insert or update based on your requirnment).

Assuming async BR--> on Insert:-

(function executeRule(current, previous /*null when async*/ ) {
    var answer = "";
    var attachmentMsg = "";
    var targetUserID = "admin";
    var targetUserPassword = "giveYourPassword";
    var targetInstanceURL = "https://dev244808.service-now.com/";

    // Update Incident
    var r = new sn_ws.RESTMessageV2('dev244808-Ebonding', 'Update-New');
    r.setStringParameterNoEscape('sys_id', current.sys_id);
    var response = r.execute();
    var responseBody = response.getBody();
    var httpStatus = response.getStatusCode();
    gs.addInfoMessage("Update-New response status: " + httpStatus);

    if (httpStatus.toString() == "200") {
        answer = "Incident successfully sent.";

        // Check for Existing Attachments
        var checkIncident = new sn_ws.RESTMessageV2('dev244808-Ebonding', 'Get Attachment');
        checkIncident.setStringParameterNoEscape('sys_id', current.sys_id);
        var checkResponse = checkIncident.execute();
        var checkResponseBody = checkResponse.getBody();
        var checkHttpStatus = checkResponse.getStatusCode();
        gs.addInfoMessage("Get Attachment response status: " + checkHttpStatus);
        var existingAttachments = JSON.parse(checkResponseBody).result;
        var existingAttachmentNames = [];

        for (var i = 0; i < existingAttachments.length; i++) {
            if (existingAttachments[i].table_sys_id == current.sys_id.toString()) {
                existingAttachmentNames.push(existingAttachments[i].file_name);
            }
        }

        gs.addInfoMessage(existingAttachmentNames.length + " matching attachment(s) found: table_sys_id matches current.sys_id");

        // Send New Attachments
        var parser = new JSONParser();
        var parsed = parser.parse(responseBody);
        var targetRec = parsed.result;
        var attachmentCount = sendAttachments(current.getTableName(), current.sys_id, targetRec.sys_id, existingAttachmentNames);
        if (attachmentCount.length > 0) {
            attachmentMsg = " Attachments successfully sent: " + attachmentCount[0] + ". Attachments failed to be sent: " + attachmentCount[1];
        } else {
            attachmentMsg = " Record had no new attachments to send.";
        }
    } else {
        gs.addInfoMessage('Failed');
    }

    answer += " " + attachmentMsg;
    gs.addInfoMessage(answer);

    function sendAttachments(sourceTable, sourceID, targetID, existingAttachmentNames) {
        var answer = [0, 0]; // successful attachments, failed attachments
        var attachmentRec = new GlideRecord("sys_attachment");
        attachmentRec.addQuery("table_sys_id", sourceID);
        attachmentRec.addQuery("table_name", sourceTable);
        attachmentRec.query();

        while (attachmentRec.next()) {
            var fileName = attachmentRec.file_name.toString();
            gs.addInfoMessage("Processing attachment: " + fileName);
            if (existingAttachmentNames.indexOf(fileName) === -1) {
                gs.addInfoMessage("Sending new attachment: " + fileName);
                var attachmentMessage = new sn_ws.RESTMessageV2();
                attachmentMessage.setHttpMethod("post");
                attachmentMessage.setBasicAuth(targetUserID, targetUserPassword);
                attachmentMessage.setEndpoint(targetInstanceURL + "api/now/attachment/file");
                attachmentMessage.setQueryParameter("table_name", sourceTable);
                attachmentMessage.setQueryParameter("table_sys_id", targetID);
                attachmentMessage.setQueryParameter("file_name", fileName);
                attachmentMessage.setRequestHeader("Content-Type", attachmentRec.content_type);
                attachmentMessage.setRequestHeader("Accept", "application/json");
                attachmentMessage.setRequestBodyFromAttachment(attachmentRec.sys_id);
                var response = attachmentMessage.execute();
                var httpStatus = response.getStatusCode();
                gs.addInfoMessage("Attachment response status: " + httpStatus);
                if (httpStatus.toString() == "201") {
                    answer[0] += 1;
                } else {
                    answer[1] += 1;
                }
            } else {
                gs.addInfoMessage("Attachment already exists: " + fileName);
            }
        }
        return answer;
    }
})(current, previous);
 
 




View solution in original post

Ravi Gaurav
Giga Sage

Can you try the below also :-- 

 

// Set the REST endpoint URL
var restEndpoint = "https://XXXXX.service-now.com/api/now/table/incident?sysparm_query=&sysparm_display_value=false&sysp..." + limit + "&sysparm_offset=" + offset;

// Set the authentication profile
var r = new sn_ws.RESTMessageV2();
r.setEndpoint(restEndpoint);
r.setHttpMethod('GET');
r.setRequestHeader('Content-Type', 'application/json');
r.setAuthenticationProfile('basic', "c8ac221adb1209900034150505961988"); // create your own basic profile

// Execute the REST API call
try {
var response = r.execute();
} catch(e) {
gs.log("ERROR: Sending REST API " + e + "\n\n" + restEndpoint, "DATA_MIGRATION_LOG");
}

// Parse the response
if (!response.haveError()) {
var parsed = JSON.parse(response.getBody());
var results = parsed.result;

// Loop through the results and create a new Incident on the target instance
results.forEach(function(item) {
var gr = new GlideRecord('incident');
gr.initialize();

// Set the Incident fields
for (var key in item) {
if (key == "sys_id") {
gr.setNewGuidValue(item[key]);
} else if (key != "sys_tags") {
gr.setValue(key, item[key]);
}
}

// Insert the new Incident
gr.autoSysFields(false);
gr.setWorkflow(false);
var recordSysId = gr.insert();

// Log any errors
if (!recordSysId) {
gs.log("NOT INSERTED: incident." + item.sys_id + " : " + gr.getLastErrorMessage(), "DATA_MIGRATION_LOG");
}
});
} else {
var responseBody = response.getBody();
var message = responseBody + "\nStatus Code: " + response.getStatusCode() + "\nError Code: " + response.getErrorCode() + "\nError Message: " + response.getErrorMessage();
gs.log("ERROR: responce REST API " + restEndpoint + "\n\n" + message, "DATA_MIGRATION_LOG");
}

View solution in original post

3 REPLIES 3

Ravi Gaurav
Giga Sage

Hi,

you can use Business Rule (async BR on Insert or update based on your requirnment).

Assuming async BR--> on Insert:-

(function executeRule(current, previous /*null when async*/ ) {
    var answer = "";
    var attachmentMsg = "";
    var targetUserID = "admin";
    var targetUserPassword = "giveYourPassword";
    var targetInstanceURL = "https://dev244808.service-now.com/";

    // Update Incident
    var r = new sn_ws.RESTMessageV2('dev244808-Ebonding', 'Update-New');
    r.setStringParameterNoEscape('sys_id', current.sys_id);
    var response = r.execute();
    var responseBody = response.getBody();
    var httpStatus = response.getStatusCode();
    gs.addInfoMessage("Update-New response status: " + httpStatus);

    if (httpStatus.toString() == "200") {
        answer = "Incident successfully sent.";

        // Check for Existing Attachments
        var checkIncident = new sn_ws.RESTMessageV2('dev244808-Ebonding', 'Get Attachment');
        checkIncident.setStringParameterNoEscape('sys_id', current.sys_id);
        var checkResponse = checkIncident.execute();
        var checkResponseBody = checkResponse.getBody();
        var checkHttpStatus = checkResponse.getStatusCode();
        gs.addInfoMessage("Get Attachment response status: " + checkHttpStatus);
        var existingAttachments = JSON.parse(checkResponseBody).result;
        var existingAttachmentNames = [];

        for (var i = 0; i < existingAttachments.length; i++) {
            if (existingAttachments[i].table_sys_id == current.sys_id.toString()) {
                existingAttachmentNames.push(existingAttachments[i].file_name);
            }
        }

        gs.addInfoMessage(existingAttachmentNames.length + " matching attachment(s) found: table_sys_id matches current.sys_id");

        // Send New Attachments
        var parser = new JSONParser();
        var parsed = parser.parse(responseBody);
        var targetRec = parsed.result;
        var attachmentCount = sendAttachments(current.getTableName(), current.sys_id, targetRec.sys_id, existingAttachmentNames);
        if (attachmentCount.length > 0) {
            attachmentMsg = " Attachments successfully sent: " + attachmentCount[0] + ". Attachments failed to be sent: " + attachmentCount[1];
        } else {
            attachmentMsg = " Record had no new attachments to send.";
        }
    } else {
        gs.addInfoMessage('Failed');
    }

    answer += " " + attachmentMsg;
    gs.addInfoMessage(answer);

    function sendAttachments(sourceTable, sourceID, targetID, existingAttachmentNames) {
        var answer = [0, 0]; // successful attachments, failed attachments
        var attachmentRec = new GlideRecord("sys_attachment");
        attachmentRec.addQuery("table_sys_id", sourceID);
        attachmentRec.addQuery("table_name", sourceTable);
        attachmentRec.query();

        while (attachmentRec.next()) {
            var fileName = attachmentRec.file_name.toString();
            gs.addInfoMessage("Processing attachment: " + fileName);
            if (existingAttachmentNames.indexOf(fileName) === -1) {
                gs.addInfoMessage("Sending new attachment: " + fileName);
                var attachmentMessage = new sn_ws.RESTMessageV2();
                attachmentMessage.setHttpMethod("post");
                attachmentMessage.setBasicAuth(targetUserID, targetUserPassword);
                attachmentMessage.setEndpoint(targetInstanceURL + "api/now/attachment/file");
                attachmentMessage.setQueryParameter("table_name", sourceTable);
                attachmentMessage.setQueryParameter("table_sys_id", targetID);
                attachmentMessage.setQueryParameter("file_name", fileName);
                attachmentMessage.setRequestHeader("Content-Type", attachmentRec.content_type);
                attachmentMessage.setRequestHeader("Accept", "application/json");
                attachmentMessage.setRequestBodyFromAttachment(attachmentRec.sys_id);
                var response = attachmentMessage.execute();
                var httpStatus = response.getStatusCode();
                gs.addInfoMessage("Attachment response status: " + httpStatus);
                if (httpStatus.toString() == "201") {
                    answer[0] += 1;
                } else {
                    answer[1] += 1;
                }
            } else {
                gs.addInfoMessage("Attachment already exists: " + fileName);
            }
        }
        return answer;
    }
})(current, previous);
 
 




Ravi Gaurav
Giga Sage

Can you try the below also :-- 

 

// Set the REST endpoint URL
var restEndpoint = "https://XXXXX.service-now.com/api/now/table/incident?sysparm_query=&sysparm_display_value=false&sysp..." + limit + "&sysparm_offset=" + offset;

// Set the authentication profile
var r = new sn_ws.RESTMessageV2();
r.setEndpoint(restEndpoint);
r.setHttpMethod('GET');
r.setRequestHeader('Content-Type', 'application/json');
r.setAuthenticationProfile('basic', "c8ac221adb1209900034150505961988"); // create your own basic profile

// Execute the REST API call
try {
var response = r.execute();
} catch(e) {
gs.log("ERROR: Sending REST API " + e + "\n\n" + restEndpoint, "DATA_MIGRATION_LOG");
}

// Parse the response
if (!response.haveError()) {
var parsed = JSON.parse(response.getBody());
var results = parsed.result;

// Loop through the results and create a new Incident on the target instance
results.forEach(function(item) {
var gr = new GlideRecord('incident');
gr.initialize();

// Set the Incident fields
for (var key in item) {
if (key == "sys_id") {
gr.setNewGuidValue(item[key]);
} else if (key != "sys_tags") {
gr.setValue(key, item[key]);
}
}

// Insert the new Incident
gr.autoSysFields(false);
gr.setWorkflow(false);
var recordSysId = gr.insert();

// Log any errors
if (!recordSysId) {
gs.log("NOT INSERTED: incident." + item.sys_id + " : " + gr.getLastErrorMessage(), "DATA_MIGRATION_LOG");
}
});
} else {
var responseBody = response.getBody();
var message = responseBody + "\nStatus Code: " + response.getStatusCode() + "\nError Code: " + response.getErrorCode() + "\nError Message: " + response.getErrorMessage();
gs.log("ERROR: responce REST API " + restEndpoint + "\n\n" + message, "DATA_MIGRATION_LOG");
}