Use WEB API Batch Request in Dynamics 365 to execute long FetchXML

By | July 27, 2018

Introduction:

Recently we had a project where we use WEB API for retrieve the records from Dynamics CRM. In our project, we dynamically create FetchXML to retrieve records but sometimes Fetchxml have a lot of columns and conditions etc so its length get increase and we this the fetchxml in URL which violates the browser URL length rule. So When we try to execute this long length FetchXML and retrieve the records using the GET method, We were getting the error message of “HTTP Error 404 – Not Found” because of WEB API request fails to execute too long FetchXML. When we work on this error message, we find that we need to use WEB API Batch Request to execute the long FetchXML.

In the below example, we execute the long FetchXML of account entity and use POST request to execute long FetchXML.

First, we created the simple request body as below:

//create request body
var bodyFetch='';
bodyFetch = '--batch_recordfetch\n'
bodyFetch += 'Content-Type: application/http\n'
bodyFetch += 'Content-Transfer-Encoding: binary\n'
bodyFetch += '\n'
bodyFetch += 'GET [CRM URL]/api/data/v8.2/accounts?fetchXml=' + fetch + ' HTTP/1.1\n'
bodyFetch += 'Content-Type: application/json\n'
bodyFetch += 'OData-Version: 4.0\n'
bodyFetch += 'OData-MaxVersion: 4.0\n'
bodyFetch += 'Prefer: odata.include-annotations=*\n'
bodyFetch += '\n'
bodyFetch += '--batch_recordfetch--'

Note: ‘fetch’ is the parameter of the long FetchXML.

And we pass the created the simple request body as data to Ajax request and we will receive the response of request as success or failure as below:

//create AJAX request
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
async: true,
url: '[CRM URL]/api/data/v8.2/' + '$batch',
data: bodyFetch,
beforeSend: function (xhr) {
//Specifying this header ensures that the results will be returned as JSON.
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("OData-MaxVersion", "4.0");
xhr.setRequestHeader("OData-Version", "4.0");
xhr.setRequestHeader("Prefer", "odata.include-annotations=*");
xhr.setRequestHeader("Content-Type", "multipart/mixed;boundary=batch_recordfetch");
},
//success callback
success: function (data, textStatus, xhr) {
data = JSON.parse(data.substring(data.indexOf('{'), data.lastIndexOf('}') + 1));
if (data != null) {
if (data.value == null) {
alert("success");
}
}
},
//error callback
error: function (xhr, textStatus, errorThrown) {
alert("failed");                          
}
});

Conclusion:

User can easily execute the long length FetchXML using the WEB API Batch Request.

To read more about FetchXML visit here.

Export Dynamics CRM Reports