WebApi batch request
The WebApi in Dynamics CRM has the option to send batch requests. This reduces the number of calls from client to server and when e.g. you need to delete a lot of records from JavaScript it saves time processing these deletes.
Unfortunately, creating a batch request is not as straight forward as doing a POST call for example. The MSDN documentation is a good starting point, but then I still had some trouble making it work. I’ve created a question on stackoverflow and the Dynamics Community. As I needed the functionality I kept trying different options and reading the documentation and I finally figured it out.
It’s very important that you build the content in the batch request as documented with MSDN. Also note that when you do a delete batch request you still need to send an empty object. With a single delete call to the api you don’t have to explicitly do this. Another things that’s a bit hard creating a batch request, the errors that are returned are not existent. You just get an empty result and you have to figure out yourself what you have done wrong.
This is the request if you’re using jQuery to do the call.
$.ajax(
{
method: 'POST',
url: 'http://crm/api/data/v8.0/$batch',
headers: {
'Content-Type': 'multipart/mixed;boundary=batch_' + batchId,
'Accept': 'application/json'
},
data: payload
});
And here’s the way to build the payload:
var data = [];
data.push('--batch_123456');
data.push('Content-Type: multipart/mixed;boundary=changeset_BBB456');
data.push('');
data.push('--changeset_BBB456');
data.push('Content-Type:application/http');
data.push('Content-Transfer-Encoding:binary');
data.push('Content-ID:1');
data.push('');
data.push('POST http://tenanturl/api/data/v8.0/accounts HTTP/1.1');
data.push('Content-Type:application/json;type=entry');
data.push('');
data.push('{ "name": "batch acount 2"}');
data.push('--changeset_BBB456');
data.push('Content-Type:application/http');
data.push('Content-Transfer-Encoding:binary');
data.push('Content-ID:1');
data.push('');
data.push('DELETE http://tenanturl/api/data/v8.1/accounts(52eb1677-427b-e611-80bb-0050568a6c2d) HTTP/1.1');
data.push('Content-Type:application/json;type=entry');
data.push('');
data.push('{}');
data.push('--changeset_BBB456--');
data.push('--batch_123456--');
var payload = data.join('\r\n');