Find your people. Pick a challenge. Ship something real. The CreatorCon Hackathon is coming to the Community Pavilion for one epic night. Every skill level, every role welcome. Join us on May 5th and learn more here.

Import and Export XML using rest api

Key Shim
Giga Contributor

Hello - we have a requirement to automate domain creation using rest api.

The issue we are facing is that the sys_id of the domain will be different across all 3 instances (prod / test / dev) if using only the rest api method. We are wondering if there's a way we can create the domain in DEV using rest api, but have a separate call to export and import the XML to the subsequent instances.

Has anyone been successful exporting and import xml between instances using rest api?

Thank you.

1 REPLY 1

Louis22
Tera Contributor

Hello, as the easiest method to do this is to use the REST API, there is no need to traverse the JSON to XML and back.

I wrote a simple class that is able to synchronize records based on the table name.

New records are created, if not avaliable on the target system.

Class:

 

 

var lib_clone = Class.create();
lib_clone.prototype = {
	tables : [],
	notFoundCount : 0,
	ldebug : new lib_debug(),
    initialize: function() {
    },
	
	setTables: function() {
		for(var i = 0; i < arguments.length; i++) {
			this.tables.push(arguments[i]);
		}
	},
	
	mainLoop: function() {
		//this.ldebug.debugFormat('lib_clone', 'start');
		for(var a = 0; a < this.tables.length; a++) {
			var gr = new GlideRecord(this.tables[a]);
			//gr.setLimit(1000);
			gr.query();
			while(gr.next()) {
				if(this.isRecordPresent(this.tables[a], gr.sys_id.toString())) {
					//this.ldebug.debugFormat('lib_clone', 'found');
				} else {
					//this.ldebug.debugFormat('lib_clone', 'not found', gr.sys_id.toString());
					this.pushRecord(this.tables[a], gr.sys_id.toString());
				}
			}
		}
		this.ldebug.debugFormat('lib_clone', 'notFoundCount', this.notFoundCount);
	},
	
	isRecordPresent: function(strtable, strsysid) {
		var request = new sn_ws.RESTMessageV2();
		request.setEndpoint('https://targetinstance1.service-now.com/api/now/table/'+strtable+'/'+strsysid);
		request.setAuthenticationProfile('basic', 'base64pw');//Base64 encoded username:password
		request.setQueryParameter('sysparm_exclude_reference_link', 'true');
		request.setHttpMethod('GET');
		request.setRequestHeader("Accept", "application/json");
		request.setRequestHeader("Content-Type", "application/json");
		var response = request.execute();
		var responseBody = response.getBody();
		var httpStatus = response.getStatusCode();
		var parsedData = JSON.parse(responseBody);
		//this.ldebug.debugFormat('lib_clone', httpStatus, responseBody);
		if(httpStatus != 404) {
			return true;
		}
		return false;
	},
	
	pushRecord: function(strtable, strsysid) {
		this.pushRecordDev(strtable, strsysid);
		this.pushRecordTest(strtable, strsysid);
	},
	
	pushRecordDev: function(strtable, strsysid) {
		this.ldebug.debugFormat('lib_clone', 'push record', strtable, strsysid);
		var gr = new GlideRecord(strtable);
		gr.get(strsysid);
		var request = new sn_ws.RESTMessageV2();
		request.setEndpoint('https://targetinstance1.service-now.com/api/xxx/v1/direct/datasync/'+strtable);
		request.setAuthenticationProfile('basic', 'base64pw');//Base64 encoded username:password
		request.setQueryParameter('sysparm_exclude_reference_link', 'true');
		var requestBody = { };
		for(var k in gr) {
			if(!gr[k].nil()) {
				requestBody[k] = gr.getValue(k);
			}
		}
		request.setRequestBody(JSON.stringify(requestBody));
		request.setHttpMethod('POST');
		request.setRequestHeader("Accept", "application/json");
		request.setRequestHeader("Content-Type", "application/json");
		//this.ldebug.debugFormat('lib_clone', 'push record', JSON.stringify(requestBody));
		var response = request.execute();
		var responseBody = response.getBody();
		var httpStatus = response.getStatusCode();
		//var parsedData = JSON.parse(responseBody);
		//this.ldebug.debugFormat('lib_clone', httpStatus, responseBody);
	},
	
	pushRecordTest: function(strtable, strsysid) {
		this.ldebug.debugFormat('lib_clone', 'push record', strtable, strsysid);
		var gr = new GlideRecord(strtable);
		gr.get(strsysid);
		var request = new sn_ws.RESTMessageV2();
		request.setEndpoint('https://targetinstance2.service-now.com/api/xxx/v1/direct/datasync/'+strtable);
		request.setAuthenticationProfile('basic', 'base64pw');//Base64 encoded username:password
		request.setQueryParameter('sysparm_exclude_reference_link', 'true');
		var requestBody = { };
		for(var k in gr) {
			if(!gr[k].nil()) {
				requestBody[k] = gr.getValue(k);
			}
		}
		request.setRequestBody(JSON.stringify(requestBody));
		request.setHttpMethod('POST');
		request.setRequestHeader("Accept", "application/json");
		request.setRequestHeader("Content-Type", "application/json");
		//this.ldebug.debugFormat('lib_clone', 'push record', JSON.stringify(requestBody));
		var response = request.execute();
		var responseBody = response.getBody();
		var httpStatus = response.getStatusCode();
		//var parsedData = JSON.parse(responseBody);
		//this.ldebug.debugFormat('lib_clone', httpStatus, responseBody);
	},

    type: 'lib_clone'
};

 

 

Scripted rest API

Louis22_0-1736511148794.png

 

 

 

(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
	var ldebug = new global.lib_debug('scripted_rest_sn_sync_target');
	//ldebug.setEnableDebug(true);
	ldebug.debugFormat('ServiceNow data Synchronization Target', 'start');
	var pathParams = request.pathParams;
	var requestString = requestBody.dataString;
	var queryParms = request.queryParams;
	var requestBody = request.body;
	var requestData = requestBody.data;
	var grt = new GlideRecord(pathParams.TableName.toString());
	grt.initialize();
	if(requestData.sys_id.toString() != "") {
		ldebug.debugFormat('ServiceNow data Synchronization Target', 'setNewGuidValue', requestData.sys_id.toString());
		var grcheck = new GlideRecord(pathParams.TableName.toString());
		grcheck.addQuery('sys_id', requestData.sys_id.toString());
		grcheck.query();
		if(grcheck.getRowCount() == 1) {
			response.setError(new sn_ws_err.ConflictError('sys_id already present on target system'));
			return response;
		}
		grt.setNewGuidValue(requestData.sys_id.toString());
	}
	for(var k in requestData) {
		if(requestData.hasOwnProperty(k)) {
			ldebug.debugFormat('ServiceNow data Synchronization Target', k, requestData[k]);
			grt[k] = requestData[k];
		}
	}
	grt.insert();
})(request, response);

 

Execute this on the source system (as it is only push mechanism currently):

 

var lclone = new lib_clone();
//lclone.setTables('sys_user', 'customer_contact', 'sys_user_grmember', 'sys_user_has_role');
lclone.setTables('sys_user', 'customer_contact');
lclone.mainLoop();