Using the REST api to create parent and child records in a single http request

I know that it is possible to insert Orders and Order Products together with a single HTTP request: Salesforce Place Order REST api p23

But when trying the same basic thing with Opportunities, I’m getting:

< HTTP/1.1 400 Bad Request
< ⋮
<[ {
“message” : “Opportunity: bad field names on insert/update call: OpportunityLineItems”,
“errorCode” : “INVALID_FIELD_FOR_INSERT_UPDATE”,
“fields” : [ “OpportunityLineItems” ]
} ]

The response above was received from the following command (line breaks added for clarity):

curl -H 'X-PrettyPrint: 1' -H 'Authorization: Bearer <sessionid>' 
https://ap4.salesforce.com/services/data/v38.0/sobjects/Opportunity -v 
-H 'Content-Type:application/json' 
-d '{"Name":"Test",
     "StageName":"ClosedWon",
     "CloseDate":"2017-01-11T12:00:00Z",
     "OpportunityLineItems":{
         "records":
            [{"Name":"TestGenWattDiesel1000kW",
               "Quantity":1,"UnitPrice":1}]
     }
    }'

Is it possible to add an Opportunity and related Opportunity Line Items in a single HTTP request, or is that something that is unique to Orders and Order Products?

Answer

I believe you request payload is correct, the URI is wrong. According to Salesforce SObject Tree, you need to send request to

/vXX.X/composite/tree/SObjectName which in your case will be https://ap4.salesforce.com/services/data/v38.0/composite/tree/Opportunity.

instead of https://ap4.salesforce.com/services/data/v38.0/sobjects/Opportunity

Also make sure that each record has attributes specifying the type and a referenceId:

'{
  "records":[
    {"attributes":{"type":"Opportunity","referenceId":"ref1"},
     "Name":"Test",
     "StageName":"ClosedWon",
     "CloseDate":"2017-01-11T12:00:00Z",
     "OpportunityLineItems":{
       "records":[
         {"attributes":{"type":"OpportunityLineItem","referenceId":"ref2"},
          "Quantity":1,
          "UnitPrice":1,
          "PricebookEntryId":"01u6F000009BK4K"}
       ]
     }
    }
  ]
}'

Update:

I read the document you shared and I believe that it is specific for order and order products.

Attribution
Source : Link , Question Author : martin , Answer Author : martin

Leave a Comment