Writing Retrieve Method Using Web API

With the release of Dynamics CRM 2016, organization data services is depreciated, so going forward we need to make sure to write scripting code using Web API only. Web API implements OData V4 and can be used for any operation that we can do using organization service, so now we can use Web API to get both data and metadata. In this article, we are providing retrieve method sample code

To use Web API we need to use URL like the following:

[Organization URI] +”/api/data/v8.0/”

Let’s take an example we want to retrieve entity specific attributes based on primary entity id, so we can create script web resource and use the following code:
  1. function retrieveEntity(entityname,id, columnset) {  
  2.     var serverURL = Xrm.Page.context.getClientUrl();  
  3.     var Query = entityname+ "(" + id + ")" + columnset;  
  4.     var req = new XMLHttpRequest();  
  5.     req.open("GET", serverURL + "/api/data/v8.0/" + Query, true);  
  6.     req.setRequestHeader("Accept""application/json");  
  7.     req.setRequestHeader("Content-Type""application/json; charset=utf-8");  
  8.     req.setRequestHeader("OData-MaxVersion""4.0");  
  9.     req.setRequestHeader("OData-Version""4.0");  
  10.     req.onreadystatechange = function() {  
  11.         if (this.readyState == 4 /* complete */ ) {  
  12.             req.onreadystatechange = null;  
  13.             if (this.status == 200)//to verify result is OK {  
  14.                 var data = JSON.parse(this.response);  
  15.                 if(data!=null && data.accountnumber!=null)
  16.                    alert(data.accountnumber);
  17.                  else {  
  18.                 var error = JSON.parse(this.response).error;  
  19.                 alert(error.message);  
  20.             }  
  21.         }  
  22.     };  
  23.     req.send();  
  24. }  
We can consume this method using following code:
  1. var Id=entityid; //primary key (GUID) , make sure you are passing GUID without {}
  2. var entityName="accounts";   
  3. var columnSet="?$select=accountnumber,address1_city"//list of column that we want to fetch  
  4.   
  5. retrieveEntity(entityName,Id,columnSet);  
  6.   

This code can be modified to work with any entity and to bring attributes based on requirement.

Stay tuned for more Web API Samples!


Similar Articles
HIMBAP
We are expert in Microsoft Power Platform.