Introduction:
In a recent project, we retrieved Dynamics 365 CRM data using WebAPI and fetchXml expressions. In most cases, we create fetchXml expressions, where we add attributes and filter conditions dynamically in the fetchXml. When we execute our dynamically created fetchXml expressions, it fails with different error messages. Here we had come across a requirement where we needed to validate the fetchXml expressions to get the proper error message before calling the retrieve WebAPI function. We had achieved this by using Dynamics 365 CRM ValidateFetchXmlExpression WebAPI function.
Please find the ValidateFetchXmlExpression WebAPI function example below, where we have passed fetchXml as input parameter with the wrong attribute name (testfield).
var fetchXml = '<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false">'+ '<entity name="account">'+ '<attribute name="name" />'+ '<attribute name="testfield" />'+ '<attribute name="primarycontactid" />'+ '<attribute name="accountid" />'+ '<order attribute="name" descending="false" />'+ '</entity>'+ '</fetch>'; //variable declartion var requestUrl = ""; var serverUrl = Xrm.Utility.getGlobalContext().getClientUrl(); //generate Web API request requestUrl += serverUrl + "/api/data/v9.2/ValidateFetchXmlExpression(FetchXml=@p1)?@p1='"+ fetchXml + "'"; //create ajax request var jqxhr = $.ajax({ type: "GET", contentType: "application/json; charset=utf-8", datatype: "json", async: false, url: requestUrl, beforeSend: function (xhr) { //Specifying this header ensures that the results will be returned as JSON. xhr.setRequestHeader("Accept", "application/json"); xhr.setRequestHeader("Content-Type", "application/json; odata.metadata=minimal"); xhr.setRequestHeader("OData-MaxVersion", "4.0"); xhr.setRequestHeader("OData-Version", "4.0"); xhr.setRequestHeader("Prefer", "odata.include-annotations=*"); } }); //check response of request if (jqxhr.responseJSON != undefined) { //get respose in object format var response = { valid: jqxhr.statusText, data: jqxhr.responseJSON }; //check for error if (jqxhr.responseJSON.error != undefined) { alert(jqxhr.responseJSON.error.message); } else { //get actual result with message var result = response.data; } }
Please find the response of WebAPI in the screenshot below:
Conclusion:
In this way, with the help of ValidateFetchXmlExpression WebAPI function, we can easily validate fetchXml expressions.