Writing Delete request using Web API

In this post we are going to discuss how we can write delete request using Web API for Dynamics CRM 2016. We can use http DELETE method in Web API for different delete scenario. For example let say we want to remove value of specific property (attribute) using Web API, so we can simply pass the property name with the record URI like below:

serverURL+"/api/data/v8.0/accounts(Record GUID)/propertyname"

So to remove that property value form the record specific to URI, so our request could be simple like below:

var serverURL=Xrm.Page.context.getClientUrl();
var req = new XMLHttpRequest();
req.open("DELETE",serverURL+"/api/data/v8.0/accounts(CBA24BEE-2DA0-E511-80DE-3863BB343AF8)/accountnumber", true);//let's say we want to remove account number
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.onreadystatechange = function () {
 if (this.readyState == 4 /* complete */) {
  req.onreadystatechange = null;
  if (this.status == 204) {
  	alert('Value removed');
    }
  else {
   var error = JSON.parse(this.response).error;
   alert(error.message);
  }
 }
};
req.send();

But if we want to remove single-valued navigation (lookup) we need to pass the single-values navigation property name and also need to append “$ref” like below:

req.open("DELETE",serverURL+"/api/data/v8.0/accounts(CBA24BEE-2DA0-E511-80DE-3863BB343AF8)/primarycontactid/$ref", true); //name of the navigation property+"$ref"

Above request will remove the lookup value form the record which means association between these records will be removed.

And finally to delete complete record we can just simply pass complete record URI like below:

var serverURL=Xrm.Page.context.getClientUrl();
var req = new XMLHttpRequest();
req.open("DELETE",serverURL+"/api/data/v8.0/accounts(CBA24BEE-2DA0-E511-80DE-3863BB343AF8)", true);
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.onreadystatechange = function () {
 if (this.readyState == 4 /* complete */) {
  req.onreadystatechange = null;
  if (this.status == 204) {
  	alert('Deleted');
    }
  else {
   var error = JSON.parse(this.response).error;
   alert(error.message);
  }
 }
};
req.send();

Stay tuned for more Web API Samples!

One thought on “Writing Delete request using Web API

  1. Pingback: Writing Delete request using Web API - Microsoft Dynamics CRM Community

Leave a Reply

Your email address will not be published. Required fields are marked *