wierd error when testing Scripted REST API
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
08-29-2024 08:49 AM
Dear all,
I have a service now dev instance where I try to test scripted Rest API feature.
The idea is to create an Incident from that REST endpoint
I have a weird error as soon as I enter some scripting in the REST API, even a simple script
The error is as below:
{"error":{"message":"Unexpected token: o","detail":"SyntaxError: Unexpected token: o (sys_script_include.d2426c9ec0a8016501958bf2ac79c775.script; line 155)"},"status":"failure"
This error occurs as long I place a single line of script as below :
var requestBody = request.body.data;
var parsedBody = JSON.parse(requestBody);if sounds like the script cannot be interpreted at all
Any idea what could it be?
regards
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
08-29-2024 08:58 AM
@User687957 It looks like
request.body.data;
Doesn't return a valid string which can be converted to an object using
JSON.parse
Please check if data property contains valid information.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
08-29-2024 09:10 AM
sorry I an newbie in this scripting,
what do you mean by JSON.Parse end check if data contains valid info
For better understanding here is the script I need to use as a sample
(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
var requestBody = request.body.data;
var parsedBody = JSON.parse(requestBody);
// Create a new incident record
var incident = new GlideRecord('incident');
incident.initialize();
incident.short_description = "test 1";
incident.description = "test 2";
incident.insert();
})(request, response);thanks for help
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
08-29-2024 09:34 AM
Hi @User687957
I have used try catch once can you check the below code and tell me the output.
var requestBody = request.body.data; gs.info('Received data: ' + requestBody); var parsedBody; try { parsedBody = JSON.parse(requestBody); gs.info('Parsed Body: ' + JSON.stringify(parsedBody)); } catch (e) { gs.error('Error parsing JSON: ' + e.message); response.setStatus(400); response.setBody({ "status": "failure", "error": { "message": "Invalid JSON", "detail": e.message } }); return; }
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
08-29-2024 09:42 AM
Hello,
it returns the following error event if I pass a correct body.
I am testing the body using REST API Explorer and POSTMAN
{
"result": {
"status": "failure",
"error": {
"message": "Invalid JSON",
"detail": "Unexpected token: o"
}
}
}regards