Amit Gujarathi
Giga Sage
Giga Sage

Hi All,

Hope you all are doing great.

In this tutorial we will be  looking into an API to add worknotes to the change request.

 

Work notes Rest Resource

(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
    // implement resource here
	return new SRChangeManagementAPI(request, response).addWorkNotes();
})(request, response);

 

SRChangeManagementAPI

var SRChangeManagementAPI = Class.create();
SRChangeManagementAPI.prototype = /** @lends x_swre_chg_api.module:sys_script_include.SRChangeManagementAPI.prototype */ {
	/**
     * Initialisation of request and response
     * 
     * @Param {any} request
     * @Param {any} response
     * @returns {undefined}
     */
	initialize: function(request, response) {
		var self = this;
		self.request = request;
		self.response = response;

		self.body = null;
		try {
			// support for POST request
			var requestBody = request.body;
			if (requestBody && requestBody.hasNext()) {
				var body = requestBody.nextEntry();
				if (body) {
					self.body = body;
				}
			}
		} catch (ignore) {
			// ignore
		}
	},

/**
     * Add the worknotes to Change Request
     * mapped to POST /api/x_swre_chg_api/changes/{id}/worknotes
     * 
     * @returns {any}
     */
	addWorkNotes: function() {

		var self = this;

		var changeId = self.getPathParam('id', '');

		if (gs.nil(changeId)) {
			return sn_ws_err.BadRequestError('id not provided in the path');
		}

		if (!self.body.hasOwnProperty('work_notes')) {
			return sn_ws_err.BadRequestError('Invalid request body: work_notes not provided');
		}

		var workNotePrefix = (function(self) {
			if (!self.body.hasOwnProperty('user_id')) {
				return '';
			}
			return gs.getMessage('User: {0} added work note:\n', [self.body.user_id]);
		})(self);

		var qry = (function() {
			return gs.getMessage('active=true^number={0}^ORsys_id={0}', changeId);
		})();

		var grChange = new GlideRecord('change_request');
		grChange.addEncodedQuery(qry);
		grChange.query();
		if (grChange.next()) {
			grChange.work_notes = workNotePrefix + self.body.work_notes;
			grChange.update();

			var err = grChange.getLastErrorMessage();
			if (!gs.nil(err)) {
				return self.getInternalServerError('Operation failed', err);
			}

		} else {
			return sn_ws_err.NotFoundError('Could not find an active Change request with id: ' + changeId);
		}

		return self.getChangeRequestResponse(grChange.getValue('sys_id'));

	},

/**
     * Get path parameter
     * 
     * @Param {String} paramName
     * @Param {String|Boolean|Integer} defaultValue
     * @returns {ConditionalExpression}
     */
	getPathParam: function(paramName, defaultValue) {
		var self = this;

		return (paramName in self.request.pathParams) ? self.request.pathParams[paramName] : defaultValue;
	},

/**
     * Custom error message
     * 
     * @Param {String} detail
     * @Param {String} message
     * @returns {Object} myError
     */
	getInternalServerError: function(detail, message) {
		var myError = new sn_ws_err.ServiceError();
		myError.setStatus(500);
		myError.setDetail(detail);
		myError.setMessage(message);
		return myError;
	},

/**
     * To derive the response object
     * 
     * @Param {any} changeSysId
     * @returns {any} out
     */
	getChangeRequestResponse: function(changeSysId) {
		var self = this;
		var out = {};

		var fields = self.getQueryParam('sysparm_fields', gs.getProperty('x_swre_chg_api.change-request.response-fields', ''));
		fields = (fields) ? fields.split(',') : [];

		var displayValue = self.getQueryParam('sysparm_display_value', 'false');

		self.response.setContentType('application/json');
		self.response.setStatus(200);

		var changeRequest = new GlideRecord('change_request');
		changeRequest.addQuery('sys_id', changeSysId);
		changeRequest.query();
		if (changeRequest.next()) {

			fields.forEach(function(fieldName) {
				fieldName = fieldName.trim();

				if (!changeRequest.isValidField(fieldName.split('.')[0]))
					return;

				var element = changeRequest.getElement(fieldName);
				var ed = element.getED(),
					value = element.toString();
				/*
                	.nil() is also true if a filed has length 0 !!
                	if (element.nil()) {
                		value = null;
                	} else
                	*/

				/*
                	if (ed.isBoolean()) {
                		value = JSUtil.toBoolean(element.toString());
                	} else if (ed.isTrulyNumber()) {
                		value = parseInt(element.toString(), 10);
                	} else {
                		value = element.toString();
                	}*/

				if ('all' == displayValue.toLowerCase()) {
					out[fieldName] = {
						display_value: element.getDisplayValue(),
						value: value
					};
				} else if ('true' == displayValue.toLowerCase()) {
					out[fieldName] = element.getDisplayValue();
				} else {
					out[fieldName] = value;
				}
			});
		}

		return out;

	},

type: 'SRChangeManagementAPI'
};

 

Request

HTTP Method / URI
POST https://swissreesmdev.service-now.com/api/x_swre_chg_api/v1/changes/CHG0703751/worknotes
Headers
Acceptapplication/json
Content-Typeapplication/json
X-UserToken4021337047eb555881b5eaf6e26d4397fe16b1e6e03fa63cab5183786c37a12dc643e117
Request Body
{"work_notes":"Test","user_id":"admin"}

 

Response

Status code
200 OK

Response Body

{
  "result": {
    "active": "true",
    "assigned_to": "",
    "assignment_group": "03cee018db25145026f8fd051d961979",
    "backout_plan": "",
    "category": "Direct Data",
    "cmdb_ci": "4654d5ee3df1304489bc9f405be032ef",
    "description": "",
    "implementation_plan": "",
    "justification": "",
    "number": "CHG0703751",
    "opened_at": "2022-12-01 13:01:15",
    "opened_by": "a0e11bb23ba32300b200655593efc491",
    "start_date": "",
    "end_date": "",
    "priority": "4",
    "requested_by": "98f3fb20f38a44f3a3b3f38449983dca",
    "risk": "4",
    "risk_impact_analysis": "",
    "short_description": "Azure DevOps Release",
    "test_plan": "",
    "u_environment": "any _change_controlled_pre_prod",
    "sys_created_by": "devops.system",
    "sys_created_on": "2022-12-01 13:01:15",
    "sys_id": "c4d9727c47e7155881b5eaf6e26d4390",
    "sys_updated_by": "S4AXNZ",
    "sys_updated_on": "2022-12-01 17:22:32",
    "watch_list": "",
    "u_testing_outcome": "successful",
    "state": "-5",
    "approval": "not requested"
  }
}

 

Please be sure to bookmark this article as well as mark it as Helpful if you thought it was helpful.

 

Regards,

Amit Gujarathi

Technomonk Youtube 

Amit Gujarathi Linkedin 

TheTechnomonk.com 

ServiceNow Community Amit Gujarathi 

 

Version history
Last update:
‎02-15-2023 10:38 PM
Updated by:
Contributors