Setting the "Content" of a REST message via script
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎05-16-2022 08:17 AM
I have a REST message that sends XML to an endpoint.
I am trying to dynamically set the "Content" of the REST message using a script.
The script I have so far:
try {
var r = new sn_ws.RESTMessageV2('TEST', 'Default POST');
var response = r.execute();
var responseBody = response.getBody();
var httpStatus = response.getStatusCode();
} catch (ex) {
var message = ex.message;
}
The XML I am trying to send in this example:
<?xml version="1.0" encoding="UTF-8"?>
<Data>
<Record>
<Action>New_Hire</Action>
<First_Name>ServiceNow</First_Name>
<Last_Name>Dev</Last_Name>
<Business_Title>Developer</Business_Title>
<Contract_Start_Date>3/30/2022</Contract_Start_Date>
<Location>Remote</Location>
<Matrix_Proposed>CW Joe Thompson</Matrix_Proposed>
</Record>
</Data>
Here is the REST message:

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎05-16-2022 08:41 AM
Hi
With "Content" if you mean body, you can set it using 'setRequestBody' and if you mean Content Type, you can use setRequestHeader'. Try using the below code -
var r = new sn_ws.RESTMessageV2('TEST', 'Default POST');
r.setRequestHeader('Content-Type','application/xml'); //pass Content Type here
r.setRequestBody(body); //body - pass your dynamic request body here
Please mark my answer as correct or helpful if applicable.
Thanks,
Aishwarya
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎05-16-2022 08:52 AM
Hi JJG
You can add 'Variable Substituions'(Use Auto generate variables) for the HTTP Method and click on Preview Script Usage button so that the code will be automatically generated for you to use.
sample code:
try {
var r = new sn_ws.RESTMessageV2('Test', 'Post Comments');
r.setStringParameterNoEscape('origin_record_number','1234');
r.setStringParameterNoEscape('comment', 'comments');
var response = r.execute();
var responseBody = response.getBody();
var httpStatus = response.getStatusCode();
}
catch(ex) {
var message = ex.message;
}
Mark it helpful if this helps you to understand. Accept solution if this give you the answer you're looking for
Kind Regards,
Rohila V
2022-25 ServiceNow Community MVP