Writing Delete Request Using Web API

In this article, 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's 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 the following:
  1. serverURL+"/api/data/v8.0/accounts(Record GUID)/propertyname"  
So to remove that property value form the record specific to URI, our request could be simple like the following,
  1. var serverURL=Xrm.Page.context.getClientUrl();  
  2. var req = new XMLHttpRequest();  
  3. 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  
  4. req.setRequestHeader("Accept""application/json");  
  5. req.setRequestHeader("Content-Type""application/json; charset=utf-8");  
  6. req.setRequestHeader("OData-MaxVersion""4.0");  
  7. req.setRequestHeader("OData-Version""4.0");  
  8. req.onreadystatechange = function () {  
  9.  if (this.readyState == 4 /* complete */) {  
  10.   req.onreadystatechange = null;  
  11.   if (this.status == 204) {  
  12.     alert('Value removed');  
  13.     }  
  14.   else {  
  15.    var error = JSON.parse(this.response).error;  
  16.    alert(error.message);  
  17.   }  
  18.  }  
  19. };  
  20. req.send();  
But if we want to remove single-valued navigation (lookup) we need to pass the single-valued navigation property name and also need to append $ref like the following,
  1. 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:
  1. var serverURL=Xrm.Page.context.getClientUrl();  
  2. var req = new XMLHttpRequest();  
  3. req.open("DELETE",serverURL+"/api/data/v8.0/accounts(CBA24BEE-2DA0-E511-80DE-3863BB343AF8)"true);  
  4. req.setRequestHeader("Accept""application/json");  
  5. req.setRequestHeader("Content-Type""application/json; charset=utf-8");  
  6. req.setRequestHeader("OData-MaxVersion""4.0");  
  7. req.setRequestHeader("OData-Version""4.0");  
  8. req.onreadystatechange = function () {  
  9.  if (this.readyState == 4 /* complete */) {  
  10.   req.onreadystatechange = null;  
  11.   if (this.status == 204) {  
  12.     alert('Deleted');  
  13.     }  
  14.   else {  
  15.    var error = JSON.parse(this.response).error;  
  16.    alert(error.message);  
  17.   }  
  18.  }  
  19. };  
  20. req.send();  
  21. }
Stay tuned for more Web API Samples!