Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

How to request servicenow REST APIs on workspace ?

KelvinY2025
Tera Contributor

This is script in "Scripted REST APIs"

 

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

    // implement resource here
    try {
        // 1. 获取请求体中的 JSON 数据
        var requestBody = request.body;
        var data = requestBody.data;

        // 2. 记录日志(调试用)
        gs.info('Received data from workspace: ' + JSON.stringify(data));

        // 3. 提取你需要的值
        var incidentNumber = data.incident_number;
        var actionType = data.action_type;
        var userId = data.user_id;

        // 4. 在这里编写你的业务逻辑
        // 例如:更新 Incident
        var grIncident = new GlideRecord('incident');
        if (grIncident.get('number', incidentNumber)) {
            grIncident.work_notes = 'Workspace action performed: ' + actionType + ' by user: ' + userId;
            grIncident.update();

            // 5. 返回成功响应
            return {
                status: 'success',
                message: 'Action processed successfully',
                incident_number: incidentNumber
            };
        } else {
            // 记录没找到的情况
            return {
                status: 'error',
                message: 'Incident not found: ' + incidentNumber
            };
        }

    } catch (e) {
        // 处理异常
        gs.error('Error processing workspace action: ' + e.message);

        return {
            status: 'error',
            message: 'Internal server error: ' + e.message
        };
    }

})(request, response);

This is UI Action BTN "workspace" script:

function onClick() {
    var incidentNumber = g_form.getValue('number');
    var userId = g_user.userID;   
    var requestData = {
        incident_number: incidentNumber,
        action_type: 'custom_workspace_action',
        user_id: userId,
        additional_data: 'any data'
    };
   
    var client = new GlideHTTPClient();
    var response = client.post(
        JSON.stringify(requestData),
        {
            "Content-Type": "application/json",
            "Accept": "application/json"
        }
    );
   
 
    if (response.getStatusCode() == 200) {
        var result = JSON.parse(response.getBody());
        if (result.status == 'success') {
            g_form.addInfoMessage('success: ' + result.message);
        } else {
            g_form.addErrorMessage('fail: ' + result.message);
        }
    } else {
        g_form.addErrorMessage('API fail,code: ' + response.getStatusCode());
    }
}

But error msg:
KelvinY2025_0-1764214688159.png

I am using GlidAjax, but it reports an error saying 'cannot access'; I use API, it tells me to use GlidAjax; I no longer know how to implement a client script to initiate a request in a workspace

0 REPLIES 0