In this blog we will learn how to fetch records of sObjects through REST API in Apex class in salesforce. Let us get started!
Prerequisites
Whitelist your Salesforce base URL in Remote Sites.
Step 1: Copy the Salesforce base URL. For example: “https://na40.salesforce.com/”.
Step 2: Go to Setup > Security Controls > Remote Site Settings .
Step 3: Click “New Remote Site” button. Enter the related Information and Save.
Fetch records of sObjects through REST API Salesforce
Apex controller code:
public with sharing class AccountRest { /** * Webkul Software. * * @category Webkul * @author Webkul * @copyright Copyright (c) 2010-2016 Webkul Software Private Limited (https://webkul.com) * @license https://store.webkul.com/license.html **/ public list<account> acc{get{ //Define http Request //append your Query to the base url HttpRequest req = new HttpRequest(); req.setEndpoint('https://'+URL.getSalesforceBaseUrl().getHost()+'/services/data/v39.0/query/?q=SELECT+Id,Name,AccountNumber,Type+FROM+Account+limit+10'); 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 str = '['+ response.substring(response.indexOf('records":[')+10,response.indexof(']}')) +']'; acc = (list<Account>)JSON.deserialize(str,list<Account>.class); return acc; }set;} }
Visualforce Page:
<apex:page controller="AccountRest"> <!-- /** * Webkul Software. * * @category Webkul * @author Webkul * @copyright Copyright (c) 2010-2016 Webkul Software Private Limited (https://webkul.com) * @license https://store.webkul.com/license.html */ --> <apex:sectionHeader title="Accounts" subtitle="List View"/> <apex:pageBlock> <apex:pageBlockTable value="{!acc}" 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.Type}"/> </apex:pageBlockTable> </apex:pageBlock> </apex:page>
Output
Support
That’s all for how to fetch records of sObjects through REST API in Apex class, still have any issue feel free to add a ticket and let us know your views to make the code better https://webkul.uvdesk.com/en/customer/create-ticket/
Leave a Comment
Comments (0)