I have a requirement to add the reference fields to the scripted rest API resource. Added those fie

Archana23
Tera Contributor

I have a requirement to add the reference fields to the scripted rest API resource.

Added those fields in the scripted rest API and testing it through postman

Getting the error like this.

 

                        "msg": "Invalid format IT Application Manager"
Is there any other format to send the reference fields (Tried with sys id also).
 
 
4 REPLIES 4

Ankur Bawiskar
Tera Patron
Tera Patron

@Archana23 

please share complete scripted REST API script and how are you testing it via postman

Share screenshots

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

This is the scripted rest resource:
 
 
(function process( /*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {

    try {

        var responseArraySuccess = [];
        var responseArrayError = [];
        var statusArray = [];

        // For each Business Application in input body
        var requestBody = request.body;
        while (requestBody.hasNext()) {
            var data = requestBody.nextEntry();
            var responseMsg = [];

            var busAppNumber = data.number;
            var fields = {
                "ermRating": {
                    "input": data.erm_rating.toString(),
                    "label": "ERM rating",
                    "field": "u_erm_rating",
                    //"pattern": /^[1-9]\.[1-9]\.[1-9]$/
                    "pattern": /$/
                },
                "biaRating": {
                    "input": data.bia_rating.toString(),
                    "label": "BIA rating",
                    "field": "u_bia_rating",
                    //"pattern": /^[1-9]\.[1-9]\.[1-9]$/
                    "pattern": /$/
                },
                "acpLevel": {
                    "input": data.acp_level.toString(),
                    "label": "ACP level",
                    "field": "u_acp_level",
                    //"pattern": /^[1-3]$/
                    "pattern": /$/
                },
                "ITApplicationManager": {
                    "input": data.it_application_owner.toString(),
                    "label": "IT Application Manager",
                    "field": "it_application_owner",
                    "isReference": "true",
                    "referenceTable": "sys_user",
                   // "pattern": /$/
                },
                // "Business Owner": {
                //     "input": data.owned_by.toString(),
                //     "label": "Business Owner",
                //     "field": "owned_by",
                //     "pattern": /$/
                // },
                "InstallStatus ": {
                    "input": data.install_status.toString(),
                    "label": " Install Status ",
                    "field": "install_status",
                    "pattern": /$/
                },
                "Add a note in activities section": {
                    "input": data.Worknote.toString(),
                    "label": "Add a note in activities section",
                    "field": "Worknotes",
                    "pattern": /$/
                },
                // "Publisher": {
                //     "input": data.manufacturer.toString(),
                //     "label": "Publisher",
                //     "field": "manufacturer",
                //     "pattern": /$/
                // },
                // "Vendor": {
                //     "input": data.Vendor.toString(),
                //     "label": "Vendor",
                //     "field": "vendor",
                //     "pattern": /$/
                // },
                // "Support Vendor": {
                //     "input": data.support_vendor.toString(),
                //     "label": "Support Vendor",
                //     "field": "support_vendor",        
                //     "pattern": /$/
                // },

            };

            // Create result object
            var resultObj = {};
            resultObj.number = busAppNumber;

            // Validate inputs
            if (!busAppNumber) {
                responseMsg.push('Invalid number');
                statusArray.push(500);

                resultObj.msg = responseMsg.join('. ');
                responseArrayError.push(resultObj);
                continue;
            }

            // Query and update Business Application
            var grBusApp = new GlideRecordSecure('cmdb_ci_business_app');
            grBusApp.addQuery('number', busAppNumber);
            grBusApp.query();
            if (grBusApp.next()) {

                for (var item in fields) {
                    var pattern = fields[item]['pattern'];
                    var field = fields[item];
                var inputValue = field.input;
                    if (fields[item]['input'] && !pattern.test(fields[item]['input']) || (fields.isReference && inputValue)) {
                        responseMsg.push('Invalid format ' + fields[item]['label'] + ' ' + fields[item]['input']);
                        statusArray.push(500);

                        resultObj.msg = responseMsg.join('. ');
                        responseArrayError.push(resultObj);
                    }else if(fields[item]['input']){
                        grBusApp.setValue(fields[item]['field'], fields[item]['input']);
                    }
                   
 
               else if(fields.isReference && inputValue) {
                    // Resolve the reference field value
                    var grRef = new GlideRecord(fields.referenceTable);
                    grRef.addQuery("name", inputValue); // Assuming "name" is the display value column
                    grRef.query();
                        gs.log("grRef" + grRef);
                    if (grRef.next()) {
                        var resolvedsysid = grRef.sys_id.toString();
                        grBusApp.setValue(field.field, resolvedsysid);
                        gs.log("resolvedsysid" + resolvedsysid);
                    } else {
                        responseMsg.push('Invalid reference value for ${field.label}: ${inputValue}');
                    }
                }
                }
                // Don't continue if errors occured
                if(responseMsg.length > 0){
                    continue;
                }

                // Check Write Access
                if (!grBusApp.canWrite()) {
                    statusArray.push(401);
                    responseMsg.push('Not authorized to update');

                    resultObj.msg = responseMsg.reverse().join('. ');
                    responseMsg.push(resultObj);
                    continue;
                }
               
                grBusApp.update();
                responseMsg.push('Updated');
                statusArray.push(200);
                resultObj.msg = responseMsg.reverse().join('. ');
                responseArraySuccess.push(resultObj);
            } else {
                responseMsg.push('Business Application not found');
                statusArray.push(500);
                resultObj.msg = responseMsg.join('. ');
                responseArrayError.push(resultObj);
            }
        }

        // Set response message
        response.setBody({
            success: [{
                count: responseArraySuccess.length.toFixed(),
                items: responseArraySuccess
            }],
            error: [{
                count: responseArrayError.length.toFixed(),
                items: responseArrayError
            }],
        });

        // Set REST status
        if (statusArray.indexOf(200) > -1) {
            response.setStatus(200);
        } else if (statusArray.indexOf(401) > -1) {
            response.setStatus(401);
        } else {
            response.setStatus(500);
        }

    } catch (e) {
        response.setBody({
            msg: e.message
        });
        response.setStatus(500);
    }

})(request, response)
 

Archana23_1-1736769345533.png

 

@Archana23 

your scripted rest api is performing some validation on each input and seems the value passed in either it_application_owner or owned_by is not a valid one

Did you check that?

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

Runjay Patel
Giga Sage

HI @Archana23 ,

 

May be you will be having syntax error, share the code here. 

Also you can check below blog, i have explained that how you can pass reference, String and other field type value.

https://servicenowwithrunjay.com/scripted-rest-api-servicenow/

https://servicenowwithrunjay.com/web-service-integration/

 

-------------------------------------------------------------------------

If you found my response helpful, please consider selecting "Accept as Solution" and marking it as "Helpful." This not only supports me but also benefits the community.


Regards
Runjay Patel - ServiceNow Solution Architect
YouTube: https://www.youtube.com/@RunjayP
LinkedIn: https://www.linkedin.com/in/runjay

-------------------------------------------------------------------------