Scripted Rest API to parse file and attach to respective user's case record

Mrman
Tera Guru

Hi ,

Can anyone help me with the below code created for scripted rest API to parse file attachment coming in request payload. 

Requirement is we get the attachment and user id from source system , then we need to attach that file to the respective case created for that user. For testing this requirement , I started developing this and created scripted rest API and trying to send the file from postman. I am getting the below mentioned error when the API is invoked in postman.

 

Scripted Rest API created in Scoped Application.

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

	var requestBody = request.body.dataString;
	var parser = new global.JSON();
	var parsedData = parser.decode(requestBody);
	var fileData = parsedData.fileData;

	var rec = new GlideRecord('sn_hr_core_case');
	rec.addQuery('number','HRC0003126');
	rec.query();
	if(rec.next()){
		if (userid == '12345'){
		var sa = new Glidesysattachment();
		sa.write(rec, fileName, fileContentType, fileData);
		response.setStatus(200)
		var responseBody = {};
		responseBody.message = "user file received successfully";
				response.setBody(responseBody);
		}
	}
	else{
		var responseBodyFailure = {};
		responseBodyFailure.status = "Failure";
		response.setBody(responseBodyFailure);
	}

})(request, response);

Below is the screenshot in Postman to send the file and Error message I am getting.

{
    "error": {
        "message": "java.util.NoSuchElementException",
        "detail": ""
    },
    "status": "failure"
}

Mrman_0-1712227552963.png

Please let me know how to successfully perform this POC and test this requiremet to test the file upload from source system to ServiceNow.

 

@Ankur Bawiskar 

9 REPLIES 9

Chetan Mahajan
Kilo Sage
Kilo Sage

Hello @Mrman ,

         This may caused by the fact that the file data variable is not being properly parsed from the request payload. This exception is typically thrown when an attempt is made to access an element that does not exist in a collection or iterator.

Try to change request.body.dataString to request.body.data

(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
   //  Use hardcoded variables for testing purposes. Replace them with the actual values from your request payload or other sources.
    var userId = '12345'; // Replace with the actual user ID
    var fileName = 'attachment.pdf'; // Replace with the actual file name
    var fileContentType = 'application/pdf'; // Replace with the actual file content type

    var rec = new GlideRecord('sn_hr_core_case');
    rec.addQuery('number', 'HRC0003126');
    rec.query();
    if (rec.next()) {
        if (userId) {
            var sa = new GlideSysAttachment();
            sa.write(rec, fileName, fileContentType, request.body.data);
            response.setStatus(200);
            var responseBody = {};
            responseBody.message = "User file received successfully";
            response.setBody(responseBody);
        }
    } else {
        var responseBodyFailure = {};
        responseBodyFailure.status = "Failure";
        response.setBody(responseBodyFailure);
    }
})(request, response);

 

@Chetan Mahajan  I have modfieid the scripted rest API as below , now the error is coming as below when I send the request from Postman. Below is the scvreenshot from postman.

"error": {
        "message": "com.glide.rest.util.RESTRuntimeException: The payload is not valid JSON."

Scripted REST API

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

    var fileName = 'Resume.pdf'; // Assuming fileName is sent in the request
    var fileContentType = 'application/pdf'; // Assuming fileContentType is sent in the request
    var userid = '12345'; // Assuming userid is sent in the request

    var rec = new GlideRecord('sn_hr_core_case');
    rec.addQuery('number', 'HRC0003126');
    rec.query();
    if (rec.next()) {
        if (userid == '12345') {
            var sa = new GlideSysAttachment();
            sa.write(rec, fileName, fileContentType, request.body.data);
            response.setStatus(200);
            var responseBody = {};
            responseBody.message = "User file received successfully";
            response.setBody(responseBody);
        }
    } else {
        var responseBodyFailure = {};
        responseBodyFailure.status = "Failure";
        response.setBody(responseBodyFailure);
    }
})(request, response);

Screenshot from postman showing the Request body and Error message

Mrman_0-1712236491429.png

Please suggest

Hi @Mrman 

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

    var fileName = request.queryParams.fileName || 'Resume.pdf'; // Assuming fileName is sent in the query parameters
    var fileContentType = request.queryParams.fileContentType || 'application/pdf'; // Assuming fileContentType is sent in the query parameters
    var userId = request.queryParams.userId || ''; // Assuming userId is sent in the query parameters

    if (userId === '12345') {
        var requestBody = request.body.data;
        
        if (!requestBody) {
            response.setError(new sn_ws_err.BadRequestError('Request body is empty'));
            return;
        }

        // Decode the base64 encoded file data
        var fileData = GlideStringUtil.base64DecodeAsBytes(requestBody);
        
        var rec = new GlideRecord('sn_hr_core_case');
        rec.addQuery('number', 'HRC0003126');
        rec.query();
        
        if (rec.next()) {
            var sa = new GlideSysAttachment();
            sa.write(rec, fileName, fileContentType, fileData);
            response.setStatus(200);
            var responseBody = {};
            responseBody.message = "User file received successfully";
            response.setBody(responseBody);
        } else {
            var responseBodyFailure = {};
            responseBodyFailure.status = "Failure";
            response.setBody(responseBodyFailure);
        }
    } else {
        response.setError(new sn_ws_err.BadRequestError('Invalid user ID'));
    }
})(request, response);

@Amit Pandey I have modified the Scripted rest API , this time I did not get any error when I triggerred reqest from Postman. However, it went Else loop even though the useID passed matches the if loop. It is always going to Else loop. Please suggest

 

Below is the screenshot from postman response.

Mrman_0-1712242211546.png

 

@Amit Pandey I started getting the below error now in postman whjen I changed the Body to 'raw' instead of form data.Please suggest

Mrman_0-1712245425519.png