← Script library

Script Includes

REST API Response Helper

Standardized functions for formatting and handling REST API responses with consistent error handling.

JavaScript
var RestResponseHelper = Class.create();
RestResponseHelper.prototype = {

  /**
   * Create success response
   * @param {object} data - Response data
   * @param {string} message - Optional success message
   * @param {number} statusCode - HTTP status code (default: 200)
   * @returns {object} Formatted response
   */
  success: function(data, message, statusCode) {
    return {
      status: 'success',
      code: statusCode || 200,
      message: message || 'Request completed successfully',
      data: data,
      timestamp: new GlideDateTime().getValue()
    };
  },

  /**
   * Create error response
   * @param {string} message - Error message
   * @param {number} statusCode - HTTP status code (default: 400)
   * @param {object} details - Additional error details
   * @returns {object} Formatted error response
   */
  error: function(message, statusCode, details) {
    return {
      status: 'error',
      code: statusCode || 400,
      message: message || 'An error occurred',
      error: details || {},
      timestamp: new GlideDateTime().getValue()
    };
  },

  /**
   * Create validation error response
   * @param {array} errors - Array of validation errors
   * @returns {object} Formatted validation error
   */
  validationError: function(errors) {
    return {
      status: 'error',
      code: 422,
      message: 'Validation failed',
      errors: errors,
      timestamp: new GlideDateTime().getValue()
    };
  },

  /**
   * Create not found response
   * @param {string} resource - Resource type (e.g., 'User', 'Incident')
   * @param {string} identifier - Resource identifier
   * @returns {object} Formatted not found response
   */
  notFound: function(resource, identifier) {
    return {
      status: 'error',
      code: 404,
      message: resource + ' not found' + (identifier ? ': ' + identifier : ''),
      timestamp: new GlideDateTime().getValue()
    };
  },

  /**
   * Create unauthorized response
   * @param {string} message - Optional message
   * @returns {object} Formatted unauthorized response
   */
  unauthorized: function(message) {
    return {
      status: 'error',
      code: 401,
      message: message || 'Unauthorized - Authentication required',
      timestamp: new GlideDateTime().getValue()
    };
  },

  /**
   * Create forbidden response
   * @param {string} message - Optional message
   * @returns {object} Formatted forbidden response
   */
  forbidden: function(message) {
    return {
      status: 'error',
      code: 403,
      message: message || 'Forbidden - Insufficient permissions',
      timestamp: new GlideDateTime().getValue()
    };
  },

  /**
   * Create paginated response
   * @param {array} data - Array of results
   * @param {number} page - Current page number
   * @param {number} pageSize - Results per page
   * @param {number} total - Total number of results
   * @returns {object} Formatted paginated response
   */
  paginated: function(data, page, pageSize, total) {
    var totalPages = Math.ceil(total / pageSize);

    return {
      status: 'success',
      code: 200,
      data: data,
      pagination: {
        page: page,
        pageSize: pageSize,
        totalResults: total,
        totalPages: totalPages,
        hasNext: page < totalPages,
        hasPrevious: page > 1
      },
      timestamp: new GlideDateTime().getValue()
    };
  },

  /**
   * Format GlideRecord as REST response
   * @param {GlideRecord} gr - GlideRecord object
   * @param {array} fields - Fields to include (optional, defaults to all)
   * @returns {object} Formatted record object
   */
  formatRecord: function(gr, fields) {
    if (!gr || !gr.isValidRecord()) {
      return null;
    }

    var record = {
      sys_id: gr.sys_id.toString(),
      sys_created_on: gr.sys_created_on.toString(),
      sys_updated_on: gr.sys_updated_on.toString()
    };

    if (fields && fields.length > 0) {
      // Include only specified fields
      fields.forEach(function(field) {
        if (gr.isValidField(field)) {
          record[field] = gr[field].toString();
          record[field + '_display'] = gr[field].getDisplayValue();
        }
      });
    } else {
      // Include all fields
      var fieldNames = gr.getFields();
      for (var i = 0; i < fieldNames.size(); i++) {
        var fieldName = fieldNames.get(i).getName();
        record[fieldName] = gr[fieldName].toString();

        // Add display value for reference fields
        if (gr[fieldName].getReferenceTable()) {
          record[fieldName + '_display'] = gr[fieldName].getDisplayValue();
        }
      }
    }

    return record;
  },

  /**
   * Format multiple GlideRecords as array
   * @param {GlideRecord} gr - GlideRecord with query results
   * @param {array} fields - Fields to include (optional)
   * @param {number} maxResults - Maximum results to return
   * @returns {array} Array of formatted records
   */
  formatRecords: function(gr, fields, maxResults) {
    var records = [];
    maxResults = maxResults || 1000;
    var count = 0;

    while (gr.next() && count < maxResults) {
      records.push(this.formatRecord(gr, fields));
      count++;
    }

    return records;
  },

  /**
   * Validate required fields in request
   * @param {object} request - Request object
   * @param {array} requiredFields - Array of required field names
   * @returns {object|null} Validation error response or null if valid
   */
  validateRequired: function(request, requiredFields) {
    var errors = [];

    requiredFields.forEach(function(field) {
      if (!request[field] || request[field] === '') {
        errors.push({
          field: field,
          message: 'Field "' + field + '" is required'
        });
      }
    });

    if (errors.length > 0) {
      return this.validationError(errors);
    }

    return null;
  },

  /**
   * Handle exception and return error response
   * @param {Error} exception - Exception object
   * @param {string} context - Context where error occurred
   * @returns {object} Formatted error response
   */
  handleException: function(exception, context) {
    var errorMsg = exception.message || exception.toString();

    gs.error(context + ': ' + errorMsg);

    return {
      status: 'error',
      code: 500,
      message: 'Internal server error',
      error: {
        context: context,
        details: gs.getProperty('glide.rest.verbose_errors') === 'true' ? errorMsg : undefined
      },
      timestamp: new GlideDateTime().getValue()
    };
  },

  type: 'RestResponseHelper'
};

How to use it

1. Create a new Script Include named 'RestResponseHelper' 2. Leave 'Client callable' unchecked 3. Copy the code above 4. Use in Scripted REST APIs: var helper = new RestResponseHelper(); // Success response response.setBody(helper.success({user: userData}, 'User found')); // Error response response.setBody(helper.error('Invalid user ID', 400)); // Not found response.setBody(helper.notFound('Incident', incNumber));

Adapt the table names, fields, and conditions to your instance. Test the behavior in a development environment before using it in production.