I am trying to send multiple attachment of incident table using rest message but i am not able to buid valid payload

Saroj Patel
Tera Expert

POST Method Content Body Configuration in Rest Message for Target Instance

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

myPostMethod content 

{
"caller_id":"${caller}",
"short_description":"${sd}",
"u_attachment":"${ecode}" 
}

 

_____________________________________________________________

 

Business Rule

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

(function executeRule(current, previous /*null when async*/ ) {

var request = new sn_ws.RESTMessageV2('Integrate with another instance', 'myPostMethod');
var att = new GlideRecord('sys_attachment');
att.addQuery('table_name', current.getTableName());
att.addQuery('table_sys_id', current.sys_id);
att.query();

var mainObj = [];


while (att.next()) {
var gsa = GlideSysAttachmentInputStream(att.sys_id.toString());
var baos = new Packages.java.io.ByteArrayOutputStream();
gsa.writeTo(baos, 0, 0);
baos.close();
var obj = {};
obj["encodedFile"] = GlideStringUtil.base64Encode(baos.toByteArray()).toString();
obj["fileName"] = att.file_name.toString();
obj["contentType"] = att.content_type.toString();
mainObj.push(obj);
}

gs.log(" Attachment Payload  :" + JSON.stringify(mainObj));    //1st log data


request.setStringParameterNoEscape('caller', current.caller_id.getDisplayValue());
request.setStringParameterNoEscape('sd', current.short_description);
request.setStringParameterNoEscape('ecode', JSON.stringify(mainObj));

var response = request.execute();
var responseBody = response.getBody();


gs.log("Response Body : " + responseBody);   //2nd log file

})(current, previous);

 

FIRST LOG FILE - successfully covert all attachment  to encoded string  and array contain 2 object because 2 file i attached in incident form. find_real_file.png

SECOND LOG FILE - its saying that my payload is not valid JSON format , How to solve this .

find_real_file.png

 

MY EXPECTED PAYLOAD

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

{
"caller_id": "Able Tuter",
"short_description": "Demo",
"u_attachment": [
                                 {
                                     "encodedFile": "U2Fyb2ogUGF0ZWw=",
                                      "fileName": "Demo.txt",
                                      "contentType": "text/plain"
                                  },
                                  {
                                     "encodedFile": "DQp2YXIgeD02ID0gamF2YSBzY3JpcHQNCg0KDQoNCg0KDQo=",
                                     "fileName": "Dummy.txt",
                                     "contentType": "text/plain"
                                   }
                             ]
}

 

NOTE => Please note that u_attachment is a field of another  instance so i want encode all attachment file in source instance and i want  to write this information  to target instance's field so that in target instance i can take a loop and decode all file and finally i will able to attach. 

but my payload is showing invalid becasue [ ] this is array object and when i am using JSON.stringfy() then it is converting in string but it should be object . I tried this syntax 

 

 and if  i am not using JSON.stringfy()  then its like  [object][object][object][object]

"u_attachment": '' [ (invalid)                                     "u_attachment":   [      =>this is  valid 

      {                                                                                                          {

      }                                                                                                            }

]"                                                                                                         ]

 

=> I provide all information please try to find out the solution for dynamic payload creation

 

1 ACCEPTED SOLUTION

Hitoshi Ozawa
Giga Sage
Giga Sage

Don't need convert to use Base64. It's also much easier to use .setRequestBodyFromAttachment() .

https://developer.servicenow.com/dev.do#!/reference/api/rome/server/sn_ws-namespace/c_RESTMessageV2A...

Example. Below script will copy all attachment from one form to another.

function copyAttachments() {
    var table_name = '<name of table with attachment to copy from>';
    var table_sys_id = '<sys_id of record to copy attachment from>';

    var att = new GlideRecord('sys_attachment');
    att.addQuery('table_name', table_name);
    att.addQuery('table_sys_id', table_sys_id);
    att.query();
    while (att.next()) {
        gs.info(att.sys_id);
        postAttachment(att);
    }
}

function postAttachment(att) {
	var instanceName = '<name of instance to attach to>';
    var user = '<user name>';
    var password = '<password>';
	var insertTableName = '<name of table to attach to>';
	var insertTableSysId = '<sys_id of record to attach to>';
    try {
        var request = new sn_ws.RESTMessageV2();
        request.setHttpMethod('post');
        request.setEndpoint("https://" + instanceName + ".service-now.com/api/now/attachment/file");
        request.setQueryParameter("table_name", insertTableName); // attach to table name
        request.setQueryParameter("table_sys_id", insertTableSysId); // attach to table record's sys_id
        request.setQueryParameter("file_name", att.file_name);
        request.setRequestHeader("Content-Type", att.content_type);
        request.setRequestHeader("Accept", "application/json");
        request.setRequestBodyFromAttachment(att.sys_id); // file to attach

        request.setBasicAuth(user, password);
        request.setRequestHeader("Accept", "application/json");

        var response = request.execute();
        var httpResponseStatus = response.getStatusCode();

        gs.info("http response status_code: " + httpResponseStatus);
    } catch (ex) {
        var message = ex.getMessage();
        gs.info(message);
    }
}

copyAttachments();

View solution in original post

3 REPLIES 3

Hitoshi Ozawa
Giga Sage
Giga Sage

Don't need convert to use Base64. It's also much easier to use .setRequestBodyFromAttachment() .

https://developer.servicenow.com/dev.do#!/reference/api/rome/server/sn_ws-namespace/c_RESTMessageV2A...

Example. Below script will copy all attachment from one form to another.

function copyAttachments() {
    var table_name = '<name of table with attachment to copy from>';
    var table_sys_id = '<sys_id of record to copy attachment from>';

    var att = new GlideRecord('sys_attachment');
    att.addQuery('table_name', table_name);
    att.addQuery('table_sys_id', table_sys_id);
    att.query();
    while (att.next()) {
        gs.info(att.sys_id);
        postAttachment(att);
    }
}

function postAttachment(att) {
	var instanceName = '<name of instance to attach to>';
    var user = '<user name>';
    var password = '<password>';
	var insertTableName = '<name of table to attach to>';
	var insertTableSysId = '<sys_id of record to attach to>';
    try {
        var request = new sn_ws.RESTMessageV2();
        request.setHttpMethod('post');
        request.setEndpoint("https://" + instanceName + ".service-now.com/api/now/attachment/file");
        request.setQueryParameter("table_name", insertTableName); // attach to table name
        request.setQueryParameter("table_sys_id", insertTableSysId); // attach to table record's sys_id
        request.setQueryParameter("file_name", att.file_name);
        request.setRequestHeader("Content-Type", att.content_type);
        request.setRequestHeader("Accept", "application/json");
        request.setRequestBodyFromAttachment(att.sys_id); // file to attach

        request.setBasicAuth(user, password);
        request.setRequestHeader("Accept", "application/json");

        var response = request.execute();
        var httpResponseStatus = response.getStatusCode();

        gs.info("http response status_code: " + httpResponseStatus);
    } catch (ex) {
        var message = ex.getMessage();
        gs.info(message);
    }
}

copyAttachments();

Thank you Its working fine .

Thank you so much .