Scripted REST API Examples
POST example 1:
(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
// implement resource here
//-- see:
//-- https://docs.servicenow.com/bundle/geneva-servicenow-platform/page/app-store/dev_portal/API_reference/ScriptableServiceRequestBody/reference/r_SSRB_data.html
//var queryParams = request.queryParams;
//var pathParams = request.pathParams;
//gs.log('PATH params: ' + path;
//gs.log('PATH param2: ' + path.description, 'wsRESTtest')
var Reqbody = request.body;
//var test_resp = pathParams.RequestDetailsJson;
var sName='';
var sID='';
var arrYesNo=false;
var requestData = Reqbody.data;
if (requestData instanceof Array) {
sName = requestData[0].name; // 'user1'
sID = requestData[0].id; // '1234'
arrYesNo=true;
} else {
sName = requestData.name; // 'user1'
sID=requestData.id;
}
response.setContentType('application/json');
response.setStatus(200);
var writer = response.getStreamWriter();
writer.writeString('sName:sID ' + sName + ',' + sID + ',arrYesNo:' + arrYesNo);
//writer.writeString('resp: ');
})(request, response);
POST example 2 - using query parameters:
(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
// implement resource here
//-- see:
//-- https://docs.servicenow.com/bundle/geneva-servicenow-platform/page/app-store/dev_portal/API_reference/ScriptableServiceRequestBody/reference/r_SSRB_data.html
response.setContentType('application/json');
response.setStatus(200);
var queryParams = request.queryParams;
var sparamtest = queryParams.TestVar1;
var writer = response.getStreamWriter();
writer.writeString('resp: OK: ' + sparamtest);
})(request, response);
The example provides a practical look at processing request data in a ServiceNow scripted REST API. The code demonstrates how request.body.data can be handled when the incoming payload may contain either a single object or an array, with instanceof Array used to determine the structure before extracting values such as name and id.
ReplyDeleteThe response-handling portion also shows how the REST response can be configured with an application/json content type, an HTTP 200 status, and a stream writer for returning output. This combination gives developers a useful practical example when working with RESTful API Training and understanding request-response processing.
The example is also relevant to full-stack development because REST APIs commonly connect frontend applications with backend services. Understanding how request payloads are structured and processed provides a useful foundation for learners progressing through JavaScript Full Stack Course.
ReplyDeleteThe handling of JSON-style request data can also be connected to applications built using the MEAN stack, where client-side JavaScript communicates with backend services through APIs. These concepts provide practical context for MEAN Stack Developer Course.
ReplyDelete