Call Salesforce REST API from Apex

In previous post, we saw that how Visualforce can be used to call Salesforce Rest API. In this short post, I would share a small piece of code to demonstrate how to use Apex to call Salesforce REST API.

First and foremost step is to add your Salesforce instance URL in Remote site settings. Once that is done, use below sample Apex code to call Salesforce REST API.

I am using API to get metadata information about Salesforce object however that can be replaced by any supported REST API of Salesforce.

//Make sure your Salesforce instance URL is added in remote site settings
String sfdcURL = URL.getSalesforceBaseUrl().toExternalForm(); 
String restAPIURL = sfdcURL + '/services/data/v29.0/sobjects/';  
HttpRequest httpRequest = new HttpRequest();  
httpRequest.setHeader('Authorization', 'OAuth ' + UserInfo.getSessionId());        
httpRequest.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionID()); 
String response = '';
try {  
		 Http http = new Http();   
		 HttpResponse httpResponse = http.send(httpRequest);  
		 if (httpResponse.getStatusCode() == 200 ) {  
			   response = JSON.serializePretty( JSON.deserializeUntyped(httpResponse.getBody()) );  
		 } else {  
			   System.debug(' httpResponse ' + httpResponse.getBody() );  
			   throw new CalloutException( httpResponse.getBody() );  
} catch( System.Exception e) {  
		 System.debug('ERROR: '+ e);  
		 throw e;  
System.debug(' ** response ** : ' + response );  

Key aspect in above code is how session Id is used as a value in OAuth and Bearer headers.


  1. Hi
    I have a canvas app with which I want to access a vf page of another org. On load of my canvas app I want to call the Api of my other org which would return the OAuth token . I would the append the returned token to the static url of the canvas app to access the page. Could you please help with the approach to be taken?

  2. Hi Jitendra sir, i am trying the same but it is throwing error for session ID :
    e [{“message”:”This session is not valid for use with the REST API”,”errorCode”:”INVALID_SESSION_ID”}]

    Could you please explain why it is happening. It would be really very helpful to me.

Leave a comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.