asifnoor
Kilo Patron

Hello,

When we integrate ServiceNow with other 3rd party systems, below are some of the common functionality that you do it

  • Fetch (List)
  • Create/Add
  • Update/Modify
  • Delete

In this article, I will show you the code on how you can do bulk delete through API. 

As you aware, ServiceNow REST API allows you to delete 1 record at a time. So in order to delete bulk records, one way is to fetch all the records that you want to delete, loop through it and call delete API one by one. Below is the sample code snippet that allows you to do this.

var request = new sn_ws.RESTMessageV2();
//modify the end point as per your requirement. i just queried incidents whose assignment group is servicedesk. you can change as per your requirement.
request.setEndpoint('https://your-instance.service-now.com/api/now/table/incident?sysparm_query=assignment_group%3Dd625dccec0a8016700a222a0f7900d06&sysparm_fields=number%2Cshort_description%2Csys_id');
request.setHttpMethod('GET');

//UPDATE AS PER YOUR INSTANCE CREDENTIALS BELOW.
var user = 'admin';
var password = 'admin';

request.setBasicAuth(user,password);
request.setRequestHeader("Accept","application/json");

var response = request.execute();
var result = response.getBody();

var result_json = JSON.parse(result);
//now loop through the results and call delete API
for(i=0;i<result_json.result.length;i++) {
  //call delete API
  request.setEndpoint('https://your-instance.service-now.com/api/now/table/incident/'+result_json.result[i].sys_id); //change end point as per your table
  request.setHttpMethod('DELETE');
  request.setRequestHeader("Accept","application/json");
  response = request.execute();
  gs.info("Record is deleted successfully"+result_json.result[i].number);
}

If you have any questions, let me know in the comments section.

Mark the article as helpful and bookmark if it finds useful.

Comments
Gokulendra Pand
Giga Contributor

I have updated my code accordingly but on execution I am getting :

{"error":{"detail":"DELETE method not supported for API","message":"Method not Supported"},"status":"failure"}

Please help me on this
 
asifnoor
Kilo Patron

Kindly share your complete script so that i can check and assist you. If its your PDI, let me know and we can check together.

Gokulendra Pand
Giga Contributor

Sorry it got resolved as I found the URL provided by me in the loop was wrong earlier. Now it's working. Thanks a lot

asifnoor
Kilo Patron

Okay, great. Would be great if you can mark my article as helpful if it helps you.

Version history
Last update:
‎08-05-2019 02:57 AM
Updated by: