[SalesForce] Bulk-API insert with sObject Tree

I am attempting to do an insert of thousands of record using the Bulk-API, which is in itself is not complicated. The thing that I am having trouble with is insert both Record and Child.
For example, I am trying to insert a new Account record and insert the new Contact its linked to at the same time. The REST API allows for that using sObject Tree however that request structure gives me the following error:

[ {"success" : false, "created" : false, "id" : null, "errors" : [ { "message" : "Account: bad field names on insert/update call: Contacts", "fields" : [ "Contacts" ], "statusCode" : "INVALID_FIELD_FOR_INSERT_UPDATE", "extendedErrorDetails" : null } ]} ]

So is there a different way of approaching this? Is it even possible to do with the BULK – API? and if so what is the proper JSON syntax?

My understanding is that the BULK – API is based on the REST API but apparently not that piece.

Best Answer

The sObject tree is only for the REST API, not the Bulk API. While they both use a REST-ful nature, only the REST API supports the sObject tree. This generally means you have to upload records in batches of 200, with a tree no more than 5 levels deep.

You can still use JSON structures with the bulk API, but it follows a slightly different format, outlined in Bulk API Relationships, and in other related documents in the Developer's Guide.

An example of using a parent-child relationship follows:

[{
  "FirstName" : "Ray",
  "LastName" : "Riordan",
  "ReportsTo" : { "Email" : "rwilliams@salesforcesample.com" }
}]

In this case, a contact named Ray Riordan is linked to a Reports To contact matching the email of rwilliams@salesforcesample.com. This is similar in nature to how the classic SOAP API can handle an indexed field relationship. However, as you'll notice, it's not the same as using the sObject tree, which relates records together using their relationship name.

The main difference between the two APIs is that the Bulk API is asynchronous and is better for many thousands of records, while the REST API is synchronous and better for real-time results on a smaller set of records. If you need to upload many thousands of records, use the Bulk API, otherwise use the REST API.