[SalesForce] Using SObject Tree REST resource to update record

I'd like to update an Account and create a child Contact in a single transaction using REST API. Tried to use SObject Tree endpoint, but when I simply pass the Id in object body, I get:

Don’t specify the record ID. It’s created automatically and returned
in the response.

Is it even possible with SObject tree? Or perhaps the Composite resource with the mix of POST and PATCH with reference notation ("AccountId": "@{refAccount.id}") is the way to go? If so, is SObject Tree just a wrapper to Composite API?

Best Answer

I don't believe this can be done via the sObject Tree resource. The documentation indicates that it's create-only:

Use the SObject Tree resource to create nested records that share a root record type. For example, in a single request, you can create an account along with its child contacts, and a second account along with its child accounts and contacts. Once the request is processed, the records are created and parents and children are automatically linked by ID.

and POST-only:

HTTP method
POST

(Emphasis mine).

Conversely, the sObject Composite takes a POST request for itself, but allows you to specify the method for each individual subrequest.

Here's a variation on the example in the linked document and the example of Account-Contact junction linking above that successfully updates an existing Account and adds a new Contact:

{
    "allOrNone" : true,
    "compositeRequest" : [{
        "method" : "PATCH",
        "url" : "/services/data/v38.0/sobjects/Account/0013600001lwxdQAAQ",
        "referenceId" : "NewAccount",
        "body" : {  
            "Name" : "TestComposite"
        }
    },
    {
        "method" : "POST",
        "referenceId" : "NewContact",
        "url" : "/services/data/v38.0/sobjects/Contact",
        "body" : {  
            "lastname" : "Doe",
            "AccountId" : "0013600001lwxdQAAQ"

        }
    }]
}

Here, we actually have to specify the Id explicitly in both requests rather than using reference Ids. That's because the reference Id names the response body for each request, so if we did @{NewAccount.id} (which works fine in a POST create operation), we'd get an error since the PATCH update response body is empty.

Related Topic