Monday, December 19, 2022

REST API with XML&JSON for Request and Response in Salesforce

Rest API architecture connecting client and database

In Previous Example I created records using Post Method from workbench. Now from this blog post am explaining how to do create record using xml/JSON with RestAPI using work bench.

Go to workbench -> Rest explorer -> Select Post radio button.
and give the URL something like this ==> /services/apexrest/v1/AccountMgmt/

as per your url mapping in your apex class:

Update apex class:


@RestResource(urlMapping='/v1/AccountMgmt/')
global class AccountMgmt {
    @httpPost
    global static Account doPostMethod(String Name, Integer AnnualRevenue){
    Account acc= new Account(Name =name,AnnualRevenue = annualrevenue);
    insert acc;
    return acc;
    }
}

In workbench Explorer Body Write like below .xml Request


<request>
<Name>Account creation using XML</Name>
<AnnualRevenue>1000</AnnualRevenue>
</request>

Now Execute:

And now suppose in future if you want to map more fields , its not easy to everytime quickly add fields in apex class. So to overcome this problem we can use Wrapper Classes
Now let’s update same apex class with Wrapper class.


@RestResource(urlMapping='/v1/AccountMgmt/')
global class AccountMgmt {
    
    @httpPost
    global static Account doPostMethod(AccountClass AcctInfo){
    Account Acct = AcctInfo.Acct;
        insert Acct;
        return Acct;
    }
     global class AccountClass{
        Account Acct { get; set; }
    }
}

Request Body in .xml Request write like below…


<request>
  <AcctInfo>
    <Acct>
       <Name>Account creation using XML</Name>
       <AnnualRevenue>1000</AnnualRevenue>
       <Phone>8867400396</Phone>
    </Acct>
  </AcctInfo>
</request>

Output:

Now Let’s try the same with JSON format file request body.. Make sure you update header from xml to json.


{
  "AcctInfo" :{
   "Acct" :{
           "Name" : "JSON Test Account",
           "AnnualRevenue" : 100,
           "Phone" : 8867400396
           }
     }
}

Output:

No comments:

Post a Comment

Understanding Wire vs Imperative Apex Method Calls in Salesforce Lightning Web Components (LWC)

Understanding Wire vs Imperative Apex Method Calls in Salesforce Lightning Web Components (LWC) Introduction: Salesforce Lightning Web ...