Running FetchXML using Xrm.WebApi in Dynamics 365

Leave a comment

In this post, we will look at how to run FetchXML using the Xrm.WebApi with JavaScript in Dynamics 365.

First, let’s create some FetchXML. We will use the FetchXML Builder in XrmToolbox to create FetchXML with single quotes. You can use your preferred tool to create FetchXML:

Now the code. We will place our FetchXML inside back ticks to create a multi-line string in JavaScript. We will then encode the FetchXML and send it to the Xrm.WebApi.

The code:

var fetchXML = `<fetch top='50' >
  <entity name='account' >
    <attribute name='name' />
    <attribute name='websiteurl' />
  </entity>
</fetch>`;

var encodedFetchXML = encodeURIComponent(fetchXML);

var req = new XMLHttpRequest();
req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v9.1/accounts?fetchXml=" + encodedFetchXML, true);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
req.onreadystatechange = function() {
    if (this.readyState === 4) {
        req.onreadystatechange = null;
        if (this.status === 200) {
            var results = JSON.parse(this.response);
        } else {
            Xrm.Utility.alertDialog(this.statusText);
        }
    }
};
req.send();

When we run this, and output the results to the console, we get our response:

 

THANKS FOR READING. BEFORE YOU LEAVE, I NEED YOUR HELP.
 

I AM SPENDING MORE TIME THESE DAYS CREATING YOUTUBE VIDEOS TO HELP PEOPLE LEARN THE MICROSOFT POWER PLATFORM.

IF YOU WOULD LIKE TO SEE HOW I BUILD APPS, OR FIND SOMETHING USEFUL READING MY BLOG, I WOULD REALLY APPRECIATE YOU SUBSCRIBING TO MY YOUTUBE CHANNEL.

THANK YOU, AND LET'S KEEP LEARNING TOGETHER.

CARL

https://www.youtube.com/carldesouza

 

ABOUT CARL DE SOUZA

Carl de Souza is a developer and architect focusing on Microsoft Dynamics 365, Power BI, Azure, and AI.

carldesouza.comLinkedIn Twitter | YouTube

 

Leave a Reply

Your email address will not be published. Required fields are marked *