Scripted REST API with XML Response

hannahrobertson
Kilo Contributor

Hi all,

I am new to ServiceNow and Scripted REST APIs. I have looked at several resources and have not been successful in getting an answer. I would like my Scripted REST API to return XML. Is this possible? It seems others are only returning XML when using SOAP.

I am able to get the output I want, but not in an appropriate format.

Below is my current Scripted REST Resource Script (Geneva). I want to return all the names of the applications in a table.
 

(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
 
var xmldoc = new XMLDocument("<myResponse></myResponse>");
var application = new GlideRecord("cmdb_ci_appl");

application.query();

  while (application.next()) {
  xmldoc.createElement("application", application.name);
}
return xmldoc.getDocumentElement().toString();

})(request, response);

After editing the script to return XML, below is my response body.

find_real_file.png


Any help would be very appreciated - thanks in advance.

Hannah

1 ACCEPTED SOLUTION

Deepa Srivastav
Kilo Sage

Hi Hannah,



I hope below blog will help you find your solution.



Scripted REST APIs - Part 2



Mark Correct if it solved your issue or hit Like and Helpful if you find my response worthy.


View solution in original post

11 REPLIES 11

olofand
Kilo Contributor

I have tested Johnv Shuns example and it works.


And its much cleaner in my opinion.



var bodyObject={testContainer:[{child1: "test"},{child2: "test"},{child3: "test"}]};


var xObject = new XMLHelper().toXMLStr(bodyObject);


var writer=response.getStreamWriter();


writer.writeString(xObject);


sailee dali
Kilo Explorer

We have similar kind of requirement in which we are customizing our Clone process where we want to downlod the table records into XML and attach it to our clone request record.

 

Can somebody help me with the logic where we can download the records via script and attach it the record.

 

I have tried this by using below code, however it create the attachment with empty XML file. I am unable to download/export and pass the xml data to the attachment.

 

 

var table = "incident";
var recordId = "d7a587674f16af00302709de0310c72c"; //using for attachment file


var gr = new GlideRecord('incident');
gr.addQuery('active','true');
var bodyObject =  gr.query();

 

var output = new XMLHelper().toXMLStr(bodyObject);

writeAttachmentFile(output);

function writeAttachmentFile(data) {

var attachment = new Attachment();
var attachmentRec = attachment.write(table, recordId, 'xyz.xml', 'xml', data);

 

I want to export few tables before cloning starts and import them back on completion of clone to ten target table.

 

 

Any help would be very appreciated