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 be done using organization service, so now we can use Web API to get both data and metadata. In this blog post we are providing retrieve method sample code
To use Web API we need to use URL like below
[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 following code:
function retrieveEntity(entityname,id, columnset) { var serverURL = Xrm.Page.context.getClientUrl(); var Query = entityname+ "(" + id + ")" + columnset; var req = new XMLHttpRequest(); req.open("GET", serverURL + "/api/data/v8.0/" + Query, 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 == 200)//to verify result is OK { var data = JSON.parse(this.response); if(data!=null && data.accountnumber!=null) alert(data.accountnumber); if(data!=null && data._primarycontactid_value!=null) alert(data._primarycontactid_value); //for lookup id } else { var error = JSON.parse(this.response).error; alert(error.message); } } }; req.send(); }
We can consume this method using following code:
var Id=entityid; //primary key (GUID) var entityName="accounts"; var columnSet="?$select=accountnumber,address1_city,_primarycontactid_value"; //list of column that we want to fetch retrieveEntity(entityName,Id,columnSet);
This code can be modified to work with any entity and to bring attributes based on requirement.You can get out of the box entity name and attributes reference from here
Stay tuned for more Web API Samples !!
Pingback: Writing retrieve method using Web API - Microsoft Dynamics CRM Community
Pingback: Writing retrievemultiple request using Web API | HIMBAP
Pingback: Writing create request using Web API | HIMBAP
1) How to retrieve Lookup fields?
2) How to get OptionSet text?
Thank you for your comments, We have updated above sample to include lookup field as well, but it will only return GUID of the lookup record to get addition detail you can use &$expand similar to the old way that we used to in REST. We will be publishing another post soon to get these additional fields like lookup and optionset test so stay tuned !!
Thank you
Pingback: Getting Formatted values using Web API | HIMBAP