I have an Apex REST endpoint that takes an SObject parameter but I can't figure out how I can pass in nested objects. Is this possible out of the box?
Let's say my endpoint's code looked like this:
@HttpPatch global static void upsertAccountAndInsertOrders(Account account) {
// The contents of this method are just for illustration.
// The code in here is irrelevant and is never run because
// the Apex REST endpoint magic tries to parse the incoming
// request into an Account object but throws an error when
// encountering the nested data.
for (Order__c order : account.Orders__r) {
// There would be a list or Order__c objects in the JSON
}
insert account.Orders__r;
upsert account;
}
I'd want to pass in JSON like this:
{"account": {"ExternalId__c": 123, "Orders__r": [{"Name": "Order to insert"}]}}
However, I get this response from the API (column number removed as it doesn't align with my simplified example):
HTTP 400 Bad Request
[{"message":"Expected JSON object to deserialize apex parameter from at [line:1, column:###]","errorCode":"JSON_PARSER_ERROR"}]
While this is just a simple example, I have deeply nested trees of objects with multiple master-detail relationships that I'd like to pass in to my Apex REST API, so it'd be ideal if I didn't have to write any additional boilerplate to make this work.
In looking at the output of JSON.serialize
for a similar object, I saw that there was a records key, so I've tried this as well:
{"account": {"ExternalId__c": 123, "Orders__r": {"records": [{"Name": "Order to insert"}]}}}
A request like this won't return an HTTP 400, but account.Orders__r.isEmpty()
(is true) and there are no records once the Apex runs.
Is it impossible to write deserialize JSON into related fields?