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.

Scripted REST API to Upload Base64 Attachments to Any Record

sunil_m_l10
Tera Expert

Sharing a reusable Scripted REST API that allows a third-party system to upload one or more attachments to any table record using Base64-encoded file data.

The API accepts:

  • table_name → Target table (incident, sc_req_item, etc.)

  • record_sys_id → Record where attachment will be added

  • attachments → Array containing file name, content type, and Base64 data

The script validates inputs and uploads attachments using GlideSysAttachment().
Useful for integrations like external portals, mobile apps, and RPA systems

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

    var responseBody = {};

    try {
        var requestBody = request.body.data;
        gs.info("Incoming Attachment Upload Request: " + JSON.stringify(requestBody));

        var tableName = requestBody.table_name;
        var recordSysId = requestBody.record_sys_id;
        var attachments = requestBody.attachments || [];

        // Validate table name
        if (!tableName) {
            response.setStatus(400);
            responseBody.message = "Missing required field: table_name";
            response.setBody(responseBody);
            return;
        }

        // Validate record
        if (!recordSysId) {
            response.setStatus(400);
            responseBody.message = "Missing required field: record_sys_id";
            response.setBody(responseBody);
            return;
        }

        // Check record exists
        var gr = new GlideRecord(tableName);
        if (!gr.get(recordSysId)) {
            response.setStatus(404);
            responseBody.message = "Record not found for table " + tableName + " with sys_id: " + recordSysId;
            response.setBody(responseBody);
            return;
        }

        // Check attachments provided
        if (!attachments.length) {
            response.setStatus(400);
            responseBody.message = "No attachments found in request body";
            response.setBody(responseBody);
            return;
        }

        // Upload all attachments
        var attachmentInfo = [];
        var gsa = new GlideSysAttachment();

        for (var i = 0; i < attachments.length; i++) {
            var att = attachments[i];

            try {
                var decodedBytes = GlideStringUtil.base64DecodeAsBytes(att.base64_data);

                var sysId = gsa.write(
                    gr,
                    att.file_name,
                    att.content_type,
                    decodedBytes
                );

                attachmentInfo.push({
                    file_name: att.file_name,
                    sys_id: sysId
                });

            } catch (e) {
                gs.error("Attachment upload failed for " + att.file_name + ": " + e.message);
            }
        }

        // Success Response
        response.setStatus(201);
        responseBody.message = "Attachments uploaded successfully";
        responseBody.table = tableName;
        responseBody.record_sys_id = recordSysId;
        responseBody.uploaded_attachments = attachmentInfo;

        response.setBody(responseBody);

    } catch (ex) {
        gs.error("Error uploading attachments: " + ex.message);

        response.setStatus(500);
        responseBody.message = "Unexpected error: " + ex.message;
        responseBody.status = "failed";

        response.setBody(responseBody);
    }

})(request, response);


Sample Request Body:

{
  "table_name": "incident",
  "record_sys_id": "d71d3c2f1b223010a3b5f9f34b4bcb3b",
  "attachments": [
    {
      "file_name": "SampleDocument.pdf",
      "content_type": "application/pdf",
      "base64_data": "JVBERi0xLjMKJcTl8uXrp/Og0MTGCjMgMCBvYmoKPDwgL0ZpbHRlciAvRmxhdGVEZWNvZGUg..."
    },
    {
      "file_name": "ImageFile.png",
      "content_type": "image/png",
      "base64_data": "iVBORw0KGgoAAAANSUhEUgAAAoAAAAHgCAYAAAA10dzkAA..."
    }
  ]
}

 

  • table_name → The table where the attachment should be added

  • record_sys_id → sys_id of the target record

  • attachments → Array of one or more files

    • file_name → Name to be used in ServiceNow

    • content_type → MIME type

    • base64_data → The file content in Base64



 

0 REPLIES 0