How to Do Complicated Queries in Dynamics 365 Customer Engagement REST Web API using Fetch XML

There are two ways to do this the first one is to use the fetchXml keyword as shown below or use Jason Lattimer’s CRM Query Builder.

var fetchXML = "<fetch>";
fetchXML += " <entity name="account">";
fetchXML += " <filter>";
fetchXML += " <condition attribute="accountid" operator="eq" value="f7b4ef42-250c-4a53-a8c5-6adfce984c93" />";
fetchXML += " </filter>";
fetchXML += " <link-entity name="principalobjectaccess" from="objectid" to="accountid" link-type="inner" alias="poa">";
fetchXML += " <attribute name="objectid" alias="objectid" />";
fetchXML += " <link-entity name="team" from="teamid" to="principalid" link-type="inner" >";
fetchXML += " <link-entity name="teammembership" from="teamid" to="teamid" link-type="inner" intersect="true" >";
fetchXML += " <link-entity name="systemuser" from="systemuserid" to="systemuserid" link-type="inner" alias="user" >";
fetchXML += " <attribute name="systemuserid" />";
fetchXML += " </link-entity>";
fetchXML += " </link-entity>";
fetchXML += " </link-entity>";
fetchXML += " </link-entity>";
fetchXML += " </entity>";
fetchXML += "</fetch>";
 var encodedFetch = encodeURI(fetchXML); //encode fetchXML
 var req = new XMLHttpRequest();
 req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data.8.2/accounts?fetchXml=" + encodedFetch, 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.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
 req.onreadystatechange = function () {
 if (this.readyState == 4 /* complete */) {
     req.onreadystatechange = null;
     if (this.status == 200) {
       var data = JSON.parse(this.response)
       successCallback(data);
     }
     else {
       errorCallback(handler);
     }
   }
 };
 req.send();

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s