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
divya manohardivya manohar 

multiple accounts with associated contacts

Hello
I have created a rest resource which will insert a single account record and can insert multiple contact records.
@RestResource(urlMapping='/BulkInsertaccountcontact/*')
global class Bulkinsert_accountcontact
{
   global class RequestBody 
   {
       Account a; //create single account
       List<Contact> cList;
   }
   
   global class myWrapper
   {
      Account a;
      List<Contact> cList;
      public string status;
      public string message;
   }
   
   @HttpPost
   global static myWrapper doPost(RequestBody rb)
   {
      RestRequest req=RestContext.request;
      RestResponse res=RestContext.response;
   
      myWrapper response=new myWrapper(); //this is object of wrapper class
      
      try
      {
        Insert rb.a;
        
        response.a=rb.a;
        
        for(Contact con:rb.cList)
        {
           con.AccountID=rb.a.ID;
        }
        
        //we need to insert contact List also
        Insert rb.cList;
        response.cList=rb.cList;
        response.status='Success';
        response.message='Created Successfully';
        
      }
      catch(exception ex)
      {
         response.a=null;
         response.cList=null;
         response.status='ERROR';
         response.Message='could not create record'+ ex.getMessage();
      }
      
      return response;
   }
}

Its working fine a but my requirement is to to create multiple account records in JSON body and each account can more than 1 contact records.

I am using workbench to test the rest resource.

I think I need to make a change as follows.
 global class RequestBody 
   {
       List<Account> a; 
       List<Contact> cList;
   }
   
   global class myWrapper
   {
      List<Account> a;
      List<Contact> cList;
      public string status;
      public string message;
   }

Please let me know how I can proceed further.

divya
Daniel BallingerDaniel Ballinger
I assume this is a follow up to your related question: json error (https://developer.salesforce.com/forums/ForumsMain?id=906F0000000DEHfIAO)

Try changing RequestBody so that it has a collection of custom object records. E.g.
 
global class RequestBody {
    List<AccountAndContacts> accounts;
}

global class AccountAndContacts {
    Account a; 
    List<Contact> cList;
}