How to develop scripted REST API with XML response

Munimohan
Tera Contributor

I have to develop an Scripted REST API which should accept Request and Response in XML format. Please  help me.


Thanks in advance.

5 REPLIES 5

Ankur Bawiskar
Tera Patron
Tera Patron

@Munimohan 

the scripted rest api can accept xml or JSON

refer links below for help

Scripted REST API example - script samples

Scripted REST API with XML Response

Scripted rest api

Scripted Rest API "PUT" method application.

Regards
Ankur

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

@Ankur Bawiskar ,

 

I tried Scripted REST API with XML Response but not working because I am getting this error "

ReferenceError: \"XMLHelper\" is not defined." as I am working in scoped application.
 
Can you please help is there any alternative for XMLHelper for scoped application.
 
Thanks,
Munimohan Bathala

@Munimohan 

there is no alternative

one workaround you can have is this

1) create a script include in global scope and accessible from all application scopes

2) pass your request xml to that script include function

3) there you can use XMLHelper

if you just want to parse the request XML in scripted rest api then you can use XMLDocument2 in scoped application

XMLDocument2

Regards
Ankur

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

@Ankur Bawiskar ,

Thanks for quick response!!!

the solution provided by helpful but I tried with below solution it worked.

 

Solution:

Created a  function it accepts in put as JSON object and return XML response. and function code find below:

 

function toXMLString(o, leaveBlanks) {
var toXml = function(v, name, ind) {
if (typeof(v) == "function")
return "";

var xml = "";
if (v instanceof Array) {
for (var i = 0, n = v.length; i < n; i++)
xml += ind + toXml(v[i], name, ind + "\t") + "\n";
} else if (typeof(v) == "object") {
var hasChild = false;
xml += ind + "<" + name;
for (var m in v) {
if (m.charAt(0) == "@")
xml += " " + m.substr(1) + "=\"" + v[m].toString() + "\"";
else
hasChild = true;
}
xml += hasChild ? ">" : "/>";
if (hasChild) {
for (var m in v) {
if (m == "#text")
xml += v[m];
else if (m == "#cdata")
xml += "<![CDATA[" + v[m] + "]]>";
else if (m.charAt(0) != "@")
xml += toXml(v[m], m, ind + "\t");
}
xml += (xml.charAt(xml.length - 1) == "\n" ? ind : "") + "</" + name + ">";
}
} else {
xml += ind + "<" + name + ">" + v.toString() + "</" + name + ">";
}
return xml;
};

xml = "";
for (var m in o)
xml += toXml(o[m], m, "");

if (leaveBlanks)
return xml;

return xml.replace(/\t|\n/g, "");

}

 

 

Thanks,

Munimohan