function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
MontTwo MontTwoMontTwo MontTwo 

How to use upsert in REST callout JSON

"Upsert" just inserts new records from JSON, but not updates existing.

It's my code:

public class myClass {
    
    @future (callout = true)
    public static void getCallout(){

        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://api.myjson.com/bins/m56qw');
        request.setMethod('GET');
        HttpResponse response = http.send(request);
        
        if (response.getStatusCode() == 200){
        	List<Object> jsonList = (List<Object>) JSON.deserializeUntyped(response.getBody());
            List<Product2> productList = new List<Product2>();
            
            for(Object o : jsonList){
                Map<String, Object> results = (Map<String, Object>) o;
                Product2 prod = new Product2();
                prod.Cost__c = Integer.valueOf(results.get('cost'));
                prod.Warehouse_Key__c = String.valueOf(results.get('sku'));  //My key to check a record
                productList.add(prod);  
            }
            if(productList != null){
                upsert productList;  //It just inserted, but not update existing records if I change them
            }
        }
    }
}
What am I doing wrong?
 
Best Answer chosen by MontTwo MontTwo
v varaprasadv varaprasad
Hi ,

If you want to update the record you need record id :
Product2 prod = new Product2();
                prod.Cost__c = Integer.valueOf(results.get('cost'));
                prod.Warehouse_Key__c = String.valueOf(results.get('sku'));  //My key to check a record
                prod.id = 'recordid'; //addrecord id
                productList.add(prod)

Hope this helps you!
If my answer helps resolve your query, please mark it as the 'Best Answer' & upvote it to benefit others.

Thanks
Varaprasad
@For  Support: varaprasad4sfdc@gmail.com