Using the Batch Resource Salesforce REST API

While coming up with a solution design for  an API integration piece for work I found the REST API batch resource feature relevant to my use case. The feature has been around since Summer 2015 and I didn’t know much about it then. Basically the batch resource allows you to make multiple request in a single API call.

I needed to come up with a simple solution for creating a single record and has option to pass an array of records to be created. I initially had been looking at 3 options and listed the things to consider on the development side.

  • REST API via the sobject resource
    • use sobject resource for record creation
    • no Apex code
    • cannot do array
  • Apex Rest API
    • accepts an array of the records
    • use of JSON parser and deserializing the request body
    • create test classes
  • Bulk API
    • last option
    • overkill for the job and too many things to consider to get the integration setup

This is where batch resource came to the rescue. With batch resource you can do maximum of 25 subrequest and it supports the sobject resource I listed on the first option. Note though that subrequests are independent, and you can’t pass information between them.

As of this writing batching is supported on the following resource with API version 34.0 and higher.

  • Limits—vXX.X/limits
  • SObject resources—vXX.X/sobjects/
  • Query—vXX.X/query/?q=soql
  • QueryAll—vXX.X/queryAll/?q=soql
  • Search—vXX.X/search/?q=sosl
  • Connect resources—vXX.X/connect/
  • Chatter resources—vXX.X/chatter/
  • Actions—vXX.X/actions

To use simply call and POST to the URI vXX.x/composite/batch

Sample JSON body

[javascript]
{
“batchRequests” :
[{
“method” : “POST”,
“url” : “v41.0/sobjects/account”,
“richInput” : {“RecordType” : {“Name” : “Sales”}, “Name” : “Account 1”}
},{
“method” : “POST”,
“url” : “v41.0/sobjects/account”,
“richInput” : {“RecordType” : {“Name” : “Sales”}, “Name” : “Account 1”}
}]
}
[/javascript]

 

Sample response

[javascript]
{
“hasErrors” : false,
“results” :
[{
“statusCode” : 201,
“result”:
{
“id” : “a4c5D00000003CGQAY”,
“success” : true,
“errors” : [ ]
}
}, {
“statusCode” : 201,
“result”:
{
“id” : “a4c5D00000003CHQAY”,
“success” : true,
“errors” : [ ]
}
}]
}
[/javascript]

So before considering Apex Rest check if batch resource can solve your problem.

Resource:

https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/resources_composite_batch.htm

https://docs.releasenotes.salesforce.com/en-us/summer15/release-notes/rn_api_rest.htm

Leave a Reply

Your email address will not be published. Required fields are marked *