+ Start a Discussion
Sachin Bhalerao 17Sachin Bhalerao 17 

Error in REST API

Dear Team ,

M working on REST API and i write following code . But m receiving error plz have a look on code and snapshot :
 
APEX Code:

public with sharing class AccountRest {
    
 
    
    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/v47.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;}
    
}

VF :

<apex:page controller="AccountRest">

   
	<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>

User-added image
Best Answer chosen by Sachin Bhalerao 17
Nayana KNayana K
Ok. Now with Url.getOrgDomainUrl()., we don't have to add endpoint in remote site setting.

req.setEndpoint(Url.getOrgDomainUrl().toExternalForm()+'/services/data/v46.0/query?q=SELECT+Id,+Name,+AccountNumber,+Type+FROM+Account+limit+10');

Just change this line and check
 

All Answers

Nayana KNayana K
As the error says, you need to add endpoint url to remote site setting. I think, adding only below url should work:
https://sachinnbhalerao-dev-ed--c.visualforce.com/services/

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_callouts_remote_site_settings.htm
Sachin Bhalerao 17Sachin Bhalerao 17
Thank you Nayana for your response i set remote settings but still same problem persists
Nayana KNayana K
Ok. Now with Url.getOrgDomainUrl()., we don't have to add endpoint in remote site setting.

req.setEndpoint(Url.getOrgDomainUrl().toExternalForm()+'/services/data/v46.0/query?q=SELECT+Id,+Name,+AccountNumber,+Type+FROM+Account+limit+10');

Just change this line and check
 
This was selected as the best answer
Sachin Bhalerao 17Sachin Bhalerao 17
Thank you Nayana , Now it is working fine .