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();
 //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;


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:pageBlockTable value="{!AccountList}" var="key">
 <apex:facet name="header">Account Name</apex:facet>
 <apex:outputLink value="/{!key.Id}">{!key.Name}</apex:outputLink>
 <apex:column value="{!key.AccountNumber}"/>
 <apex:column value="{!key.Phone}"/> 



View More:


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.

Warning: mysqli_num_fields() expects parameter 1 to be mysqli_result, bool given in C:\inetpub\vhosts\debugonweb.com\httpdocs\wp-includes\wp-db.php on line 3353