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

REST API with XML&JSON for Request and Response in Salesforce
by: jayakrishnasfdc
blow post content copied from  Jayakrishna Ganjikunta
click here to view original post


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:


January 03, 2021 at 04:00PM
Click here for more details...

=============================
The original post is available in Jayakrishna Ganjikunta by jayakrishnasfdc
this post has been published as it is through automation. Automation script brings all the top bloggers post under a single umbrella.
The purpose of this blog, Follow the top Salesforce bloggers and collect all blogs in a single place through automation.
============================

Salesforce