Scripted Rest API — any way to get rid of the "result"  wrapper?

Joey Day
Giga Guru

When writing my own Scripted REST API, in the Scripted API Resource record, I'm specifying the object I'd like serialized and returned to the requestor. I've tried writing the Scripted API Resource script two different ways, like this:

(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {

        // implement resource here

        return {

                  "text": "Hello world!"

        };

})(request, response);

And alternatively like this:

(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {

        // implement resource here

        response.setBody({

                  "text": "Hello world!"

        });

})(request, response);

But, either way, ServiceNow wraps that returned object in another object containing a single key/value pair named "result" and the value being the object I returned. So, the serialized JSON ServiceNow actually sends back looks like this:

{"result":{"text":"Hello world!"}}

Is there any way to get rid of this "result" wrapper? I didn't write the system that'll receive this response and I need the returned JSON to be formatted to their strict specification or my integration won't work.

1 ACCEPTED SOLUTION

dave_slusher
ServiceNow Employee
ServiceNow Employee

In the circumstance where you want full control,   you can do response.getStreamWriter() which will give you that object.   Write your response to that and it won't be wrapped in the result object.  



The downside is that it won't automatically response to the Accept headers when you do that.   If that is important,   you'll have to branch on them inside your code,   writing the JSON string one way or the XML string the other.



Make sense?


View solution in original post

7 REPLIES 7

dave_slusher
ServiceNow Employee
ServiceNow Employee

And I should have mentioned in my original response you have to do this in any situation where you need your results to conform to a given format. My favorite Scripted REST API use case is conforming an instance to an existing API, like when I put a subset of Twitter API over Live Feed. Nothing in the world expects "result" as the root node of a response, so you always have to do this in those cases.


Yep, I'm building mine here to conform to the Slack API. 🙂


pawan k singh
Tera Guru

Use below script 

//Send Response
var jsonObj = {"Name": "Pawan", "Age" : 28, "Address" :"abc"}, // Get your JSON data in variable jsonObj 
    response.setContentType('application/json');
    response.setStatus(200);
    var writer = response.getStreamWriter();
    writer.writeString(JSON.stringify(jsonObj)); // Stringify before sending JSON

// Output will be 
 {"Name": "Pawan", "Age" : 28, "Address" :"abc"}

Please mark this answer helpful, if it helped you.

Regards

Pawan K Singh