Dynamics 365 V9 includes the new Xrm.WebApi helpers that allow you to access the Dynamics 365 Web API without having to create your own requests. The Xrm.WebApi.retrieveMultipleRecords method allows you to easily retrieve records, but the examples on MSDN only demonstrate how to use this using the OData query options. It is possible however to also use fetchXML queries instead.
For this example the fetchXML query we want to use is below:
To use this query in the retrieveMultipleRecords function, we first want to encode the fetchXML, as this will need to be valid for use in a URL. We can do this with the encodeURIComponent javascript function. We secondly want to prepend the fetchXML with ?fetchXML= , which will instruct the API that we are sending a fetchXML query.
Now that we have our query we can now use it in the retrieveMultipleRecords function like below:
Note that the entity parameter and the entity being retrieved need to match, otherwise an error will be returned.
Also keep in mind that Internet Explorer and Edge only support up to 2047 characters in a URL, so very large fetchXml queries will cause an error in those browsers.
In this example we are printing retrieved contacts to the console, which look like this: