Inbound REST API for receiving attachments and field information to Case table

maneesh3
Tera Contributor

Hi Team,

 

We are working on SNOW to SNOW integration through REST API between incident data and Case data.  Below is the scripted web service code but unable to get attachments and comments data, kindly help for fix:

 

(function process(request, response) {
 
    // Parse the request body
    var body = request.body.dataString;
    var payload = JSON.parse(body);
 
    // Extract key data from the payload
    var comments = payload.comments;
    var state = payload.state;
    var priority = payload.priority;
    var short1 = payload.short_description;
    var desc1 = payload.description;
    var custnum = payload.number;
 //gs.log(payload.comments, 'voxai_log_test3');
    // Initialize attachment data (if available)
    var file_name = payload.attachment ? payload.attachment.file_name : null;
    var content_type = payload.attachment ? payload.attachment.content_type : null;
    var hash = payload.attachment ? payload.attachment.hash : null;
    var table_name = payload.attachment ? payload.attachment.table_name : null;
    var correlationID = payload.attachment.table_sys_id
                        ? payload.attachment.table_sys_id
                        : payload.sys_id;  // Default to sys_id if not provided in attachment
 
    // Initialize message and case number for response
    var message = '';
    var number = '';  // Initialize number early to ensure it's always populated
 
    // Query to find an existing case using correlation_id or sys_id
    if (JSUtil.notNil(custnum) && JSUtil.notNil(correlationID)) {
        var importTable = new GlideRecord('sn_customerservice_case');
        importTable.addQuery("correlation_id", correlationID);  // Querying by correlation_id
        importTable.query();
 
        if (!importTable.next()) {  // No existing case, creating a new one
            importTable.initialize();
            importTable.state = state;
            importTable.u_genesys_ticket = comments;
            importTable.priority = priority;
            importTable.correlation_id = correlationID;
            importTable.short_description = short1;
            importTable.description = desc1;
            importTable.u_customer_ticket = custnum;
            importTable.insert();  // Insert the new case record
            message = 'Case created successfully';
            number = importTable.number;
        } else {  // Existing case found, updating it
            importTable.state = state;
            importTable.u_genesys_ticket = comments;
            importTable.priority = priority;
            importTable.short_description = short1;
            importTable.description = desc1;
            importTable.update();  // Update the existing case record
            message = 'Case updated successfully';
            number = importTable.number;
        }
 
    }
 
    // Handle file attachment (if any)
    else if (JSUtil.notNil(file_name) && JSUtil.notNil(content_type) && JSUtil.notNil(hash) && JSUtil.notNil(correlationID)) {
        var attachmentRecord = new GlideRecord('sn_customerservice_case');
        if (attachmentRecord.get('correlation_id', correlationID)) {  // Ensure we are looking at the correct case
            try {
                var sa = new GlideSysAttachment();
                sa.write(attachmentRecord, file_name, content_type, hash);  // Attach the file to the case
                number = attachmentRecord.number;
                message = 'Attachment processed successfully.';
            } catch (e) {
                // Log an error if file attachment fails
                gs.log('Error attaching file: ' + e.message, 'Case Process');
                message = 'Error attaching file.';
                return updateResponse(number, message, 500);  // Return with 500 Internal Server Error if attachment fails
            }
        } else {
            // Log an error if the correlation_id doesn't match any case
            gs.log('No case found for correlation_id: ' + correlationID, 'Case Process');
            message = 'Invalid case for attachment.';
            return updateResponse(number, message, 400);  // Return immediately with error status for attachment mismatch
        }
    }else {
        message = 'Invalid case';
        number = 'NA';  // Ensure number is populated with 'NA' for invalid cases
        return updateResponse(number, message, 400);  // Return immediately with error status
    }
 
    // Prepare response body
    function updateResponse(number, message, statusCode) {
        // Ensure caseNumber and message are strings and handle edge cases
        var responseBody = {
            caseNumber: number || '',  // Ensure this is a string (empty string if undefined)
            message: message || ''  // Ensure this is a string
        };
 
        // Set response status and body
        response.setStatus(statusCode || 200);  // Use provided statusCode, default to 200
        response.setContentType('application/json');
        response.setBody(responseBody);  // Ensure response is JSON stringified
    }
 
    // Call the updateResponse function to send the response
    updateResponse(number, message, 200);
 
})(request, response);
 
 
Thanks for support

 

 

2 REPLIES 2

mahemoodhus
Tera Contributor

Here the code easily you can achieve the snow-to-snow integration,

Your code for integrating attachments and comments between ServiceNow instances using REST APIs has a solid foundation but requires some corrections and refinements to handle attachments and comments properly. Here's the updated and fixed version of your script

(function process(request, response) {
// Parse the request body
var body = request.body.dataString;
var payload = JSON.parse(body);

// Extract key data from the payload
var comments = payload.comments;
var state = payload.state;
var priority = payload.priority;
var short1 = payload.short_description;
var desc1 = payload.description;
var custnum = payload.number;

// Initialize attachment data (if available)
var attachment = payload.attachment || {};
var file_name = attachment.file_name;
var content_type = attachment.content_type;
var base64Data = attachment.data; // Assuming data is base64-encoded content
var correlationID = payload.correlation_id || payload.sys_id;

// Initialize message and case number for response
var message = '';
var number = '';

// Query to find an existing case using correlation_id or sys_id
if (JSUtil.notNil(custnum) && JSUtil.notNil(correlationID)) {
var caseRecord = new GlideRecord('sn_customerservice_case');
caseRecord.addQuery('correlation_id', correlationID);
caseRecord.query();

if (!caseRecord.next()) {
// No existing case, create a new one
caseRecord.initialize();
caseRecord.state = state;
caseRecord.u_genesys_ticket = comments;
caseRecord.priority = priority;
caseRecord.correlation_id = correlationID;
caseRecord.short_description = short1;
caseRecord.description = desc1;
caseRecord.u_customer_ticket = custnum;
caseRecord.insert();

message = 'Case created successfully';
number = caseRecord.number;
} else {
// Existing case found, update it
caseRecord.state = state;
caseRecord.u_genesys_ticket = comments;
caseRecord.priority = priority;
caseRecord.short_description = short1;
caseRecord.description = desc1;
caseRecord.update();

message = 'Case updated successfully';
number = caseRecord.number;
}

// Add comments if available
if (JSUtil.notNil(comments)) {
var journalEntry = new GlideRecord('sys_journal_field');
journalEntry.initialize();
journalEntry.name = caseRecord.sys_id;
journalEntry.element = 'comments';
journalEntry.value = comments;
journalEntry.insert();
}
}

// Handle file attachment (if any)
if (JSUtil.notNil(file_name) && JSUtil.notNil(content_type) && JSUtil.notNil(base64Data) && JSUtil.notNil(correlationID)) {
var caseForAttachment = new GlideRecord('sn_customerservice_case');
if (caseForAttachment.get('correlation_id', correlationID)) {
try {
var sa = new GlideSysAttachment();
var decodedData = GlideStringUtil.base64Decode(base64Data); // Decode base64 content
sa.write(caseForAttachment, file_name, content_type, decodedData);

number = caseForAttachment.number;
message = 'Attachment processed successfully';
} catch (e) {
gs.error('Error attaching file: ' + e.message, 'SNOW to SNOW Integration');
message = 'Error processing attachment';
return sendResponse(number, message, 500);
}
} else {
message = 'Invalid correlation ID for attachment';
return sendResponse(number, message, 400);
}
}

// Prepare response
function sendResponse(number, message, statusCode) {
var responseBody = {
caseNumber: number || '',
message: message || ''
};

response.setStatus(statusCode || 200);
response.setContentType('application/json');
response.setBody(responseBody);
}

// Send the final response
sendResponse(number, message, 200);
})(request, response);
Payload for Testing: Ensure the attachment.data field in the payload contains base64-encoded content. Example:
{
"number": "INC0010001",
"state": "In Progress",
"priority": "High",
"short_description": "Test Incident",
"description": "This is a test",
"comments": "Adding a comment via API",
"correlation_id": "12345",
"attachment": {
"file_name": "test_file.txt",
"content_type": "text/plain",
"data": "dGVzdCBmaWxlIGNvbnRlbnQ="
}
}


Thank you mahemoodhus, I will connect with other side of SNOW instance and update . Thank you for your support