To get started with querying the Web API via FetchXML you are going to need some FetchXML. Feel free to write it manually or by using your favorite editor/generator. For this example I’m going to use the functionality that Dynamics 365 has built in for generating FetchXML queries – the Advanced Find.
If you aren’t familiar with the Advanced Find feature of Dynamics 365, you can access it by clicking the filter symbol in the top navigation bar of your Dynamics 365 environment.
Open the downloaded file with your favorite text editor and you should have something that resembles a query like the one below.
<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false">
<attribute name="name" />
<attribute name="primarycontactid" />
<attribute name="telephone1" />
<attribute name="accountid" />
<order attribute="name" descending="false" />
<condition attribute="name" operator="like" value="C%" />
var fetchXml = "<fetch version=\"1.0\" output-format=\"xml-platform\" mapping=\"logical\" distinct=\"false\">" +
"<entity name=\"account\">" +
"<attribute name=\"name\" />" +
"<attribute name=\"primarycontactid\" />" +
"<attribute name=\"telephone1\" />" +
"<attribute name=\"accountid\" />" +
"<order attribute=\"name\" descending=\"false\" />" +
"<filter type=\"and\">" +
"<condition attribute=\"name\" operator=\"like\" value=\"C%\" />" +
var encodedFetchXml = encodeURI(fetchXml);
From there we can build the full request URL by combining the encoded FetchXML with a predictable path as well as the client URL which we will get using the standard Xrm.Page.context.getClientUrl() function. Note that “accounts” in the example below should be replaced with the entity name you are trying to query.
var queryPath = "/api/data/v8.0/accounts?fetchXml=" + encodedFetchXml;
var requestPath = Xrm.Page.context.getClientUrl() + queryPath;
With our request path string built, we can perform a standard XmlHttpRequest to retrieve the data from the web service and work with the results however we wish.
var req = new XMLHttpRequest();
req.open("GET", requestPath, true);
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.onreadystatechange = function ()
if (this.readyState === 4)
this.onreadystatechange = null;
if (this.status === 200)
var returned = JSON.parse(this.responseText);
var results = returned.value;
for (var i = 0; i < results.length; i++)
var accountName = results[i]["name"];
var primaryContactId = results[i]["_primarycontactid_value"];
var telephone = results[i]["telephone1"];
var accountId = results[i]["accountid"];
//TODO: Implement logic for handling results as desired
And that’s all there is to it. If you are ever unsure of how to work with the returned results simply use the debugger within your browser to examine the structure of the results object itself.