The CreatorCon Call for Content is officially open! Get started here.

How to validate mandatory variables through REST API?

User205031
Tera Contributor

Hi All,

 

I am trying to submit a catalog item and  using Service Catalog REST API (OOTB). I want to check validation for mandatory variables. I am passing the below parameters with one mandatory variable value as empty but still it is creating REQ. It should not create a REQ and show an error message 'Mandatory Variables are required'

 
Request Body:
User205031_0-1760001374246.png

 

 
Response Body:
User205031_2-1760001481029.png

 


 

 

How do I fix this issue so that it will through Mandatory variables check error?

 

Please help!

3 REPLIES 3

Laveena-Agarwal
Kilo Sage

M Iftikhar
Giga Sage

@User205031 ,

You need to implement server-side validation before allowing REQ creation.

If you’re calling the OOTB API externally, you can wrap it with a custom Scripted REST API.

(function process(request, response) {
  var body = request.body.data || {};
  var itemSysId = body.sysparm_id || body.cat_item || body.cat_item_sys_id;
  if (!itemSysId) {
    response.setStatus(400);
    response.setBody({ error: 'Missing catalog item sys_id (sysparm_id/cat_item)' });
    return;
  }

  var variables = body.variables || {};
  var optGR = new GlideRecord('item_option_new');
  optGR.addQuery('cat_item', itemSysId);
  optGR.addQuery('mandatory', true);
  optGR.addQuery('active', true);
  optGR.query();

  var missing = [];
  while (optGR.next()) {
    var key = optGR.getValue('variable_name') || optGR.getValue('name') || optGR.getValue('question_text') || optGR.getValue('sys_id');

    var supplied = Object.prototype.hasOwnProperty.call(variables, key) ? variables[key] : undefined;
    var isMissing = (supplied === undefined || supplied === null );

    if (isMissing) {
      missing.push({ key: key, question: optGR.getDisplayValue('question_text') || optGR.getDisplayValue('name') });
    }
  }

  if (missing.length > 0) {
    response.setStatus(400);
    response.setBody({
      error: 'Mandatory Variables are required',
      missing: missing
    });
    return;
  }

  // All good then call the OOTB API to create the RITM 
})(request, response);

 

Thanks & Regards,
Muhammad Iftikhar

If my response helped, please mark it as the accepted solution so others can benefit as well.

Ankur Bawiskar
Tera Patron
Tera Patron

@User205031 

if the variable is mandatory at Variable Config level then it will throw error.

If any UI policy or client script is making that variable mandatory then Service Catalog API won't check that

You need a custom logic for that which is shared below

Service Catalog REST API - ORDERNOW to check all M... - ServiceNow Com

💡 If my response helped, please mark it as correct ✔️ and close the thread 🔒 — this helps future readers find the solution faster! 🙏

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