Calling Web API with FetchXML in JavaScript

This functionality has been available in Dynamics 365 Web API for sometime, and here is the Microsoft article on some examples: https://msdn.microsoft.com/en-nz/library/mt607533.aspx

However, there was a bug previously exist in Web API that has been recently corrected and the fix has been released to Dynamics 365 Online around the 1st June 2017. The previous bug was that when the Web API receives the FetchXML request, it decodes the featchXML parameter twice. And as a workaround, we will need to perform encoding twice before the request is sent, like below.

var fetchXml = encodeURIComponent('your fetchXml goes in here');
var req = new XMLHttpRequest();
req.open("GET", _webApiPath() + encodeURIComponent("accounts?fetchXml=" + fetchXml), true); 
req.setRequestHeader("Accept", "application/json"); 
req.setRequestHeader("Content-Type", "application/json; charset=utf-8"); 
req.setRequestHeader("OData-MaxVersion", "4.0"); 
req.setRequestHeader("OData-Version", "4.0");

If you don't encode twice, the WebAPI will return "Invalid XML" error message in the response.

Recently, the fix to the double decoding issue has been released to Dynamics 365 Online, the above working code started to result in "Invalid XML" error. That is because Web API only decodes once, and the passed in FetchXML value is not in a valid XML format.

The solution is pretty obvious, we just need to remove one of the encoding in the code, then Web API request will work fine again.

Comments

Popular posts from this blog

Dynamics 365 sub-grid add new and add existing

Dynamics 365 Web API get entity using alternate key value that has apostrophe/single quote in it

TLS 1.2 and PowerShell