Using FetchXML in Web API Queries via JavaScript for Dynamics 365

April 18, 2017

First introduced in CRM 2016, the Web API in Dynamics 365 contains the ability to execute FetchXML queries.

This is significant because FetchXML exists in numerous places in Dynamics 365, which means easy access to the tools and skills to support them. That’s not to say oData doesn’t have its place, but having a restful way to execute FetchXML queries provides us another avenue to create custom dashboard components and other JavaScript customizations quickly and easily.

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.


 

A window will pop up that will allow you to build a query using a WYSIWYG editor. Once you have defined a query you are happy with you can click the Download Fetch XML button in the ribbon to get a file containing the query we will be using in our JavaScript code.



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">

  <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%" />

    </filter>

  </entity>

</fetch>


 
Now that we have a query we can begin working on the JavaScript that will execute this query so that we can use the returned data in our dashboard, form event, or whatever kind of JavaScript customization you are trying to write.

First of all, the FetchXML needs to be in a format usable by the Web API service endpoint. We do this by storing the FetchXML in a variable and encoding the string with the encodeURI function native to JavaScript.
 

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%\" />" +

                    "</filter>" +

                  "</entity>" +

                "</fetch>";

 

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("Accept", "application/json");

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

            }

        }

        else

        {

            alert(this.statusText);

        }

    }

};

req.send();


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.
With the above knowledge you should be able to use any FetchXML query with JavaScript and the Web API as needed.

 

Tyler Hoffmann
About the Author

Tyler Hoffmann
Software Engineer

Tyler is a software engineer for Heartland Business Systems who works with all aspects of Dynamics 365. As a developer at heart, Tyler specializes in writing .NET and JavaScript customizations for Dynamics 365 and is enjoying getting his hands dirty with PowerApps and Flow. In addition to writing code, Tyler also has extensive experience with the implementation, configuration, and administration of Dynamics 365 and its supporting services. 

Share

Title Text

Subtitle Text