Hi folks, In this tutorial I am going to show you how to fetch records from sobjects using REST API in apex class salesforce. This is also an approach to overcome salesforce “Too Many Query Rows 50001” limit exception.

How to fetch records from sobjects using REST API in apex class salesforce:

Before starting add your salesforce base url to remote setting in my case i have added https://devlighting-dev-ed–c.na46.visual.force.com to remote setting to whitelist my salesforce URL.

Create Apex Controller:

Step 1- Goto Setup and open Developer Console.

Step 2- Create an apex class called RESTAccountController. Replace the following code in the class.

public class RESTAccountController {
 public List<Account> AccountList { get
 {
 
 HttpRequest req = new HttpRequest();
 req.setEndpoint('https://'+URL.getSalesforceBaseUrl().getHost()+'/services/data/v39.0/query/?q=SELECT+Id,Name,AccountNumber,Phone+FROM+Account');
 req.setMethod('GET');
 
 //Get SessionId
 string autho = 'Bearer '+userInfo.getSessionId();
 req.setHeader('Authorization', autho);
 
 //Get Response
 Http http = new Http();
 HTTPresponse res= http.send(req);
 string response = res.getBody();
 
 //Deserialize obtained json response
 string sData = '['+ response.substring(response.indexOf('records":[')+10,response.indexof(']}')) +']';
 List<Account> lstAccount = (list<Account>)JSON.deserialize(sData,list<Account>.class);
 return lstAccount;
 
 }
 set;
 }
}

Where,

URL.getSalesforceBaseUrl().getHost(): is used to get host name from salesforce base url

string autho = ‘Bearer ‘+userInfo.getSessionId();
req.setHeader(‘Authorization’, autho);

This line of code is used to authorize your request.

Create Visualforce Page:

Create a Visualforce Page called DisplayAccount. Write the following code.

<apex:page controller="RESTAccountController">
 
 <apex:sectionHeader title="Accounts" subtitle="List View"/>
 <apex:pageBlock>
 
 <apex:pageBlockTable value="{!AccountList}" var="key">
 
 <apex:column>
 <apex:facet name="header">Account Name</apex:facet>
 <apex:outputLink value="/{!key.Id}">{!key.Name}</apex:outputLink>
 </apex:column>
 <apex:column value="{!key.AccountNumber}"/>
 <apex:column value="{!key.Phone}"/> 
 
 </apex:pageBlockTable>
 
 </apex:pageBlock>
 
</apex:page>

Output:

REST API

View More:

Conclusion:

I hope you would love this post. Please don’t hesitate to comment for any technical help. I would appreciate your feedback and suggestions.

Thank You.

Leave a Comment