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.




Related Posts


8 responses to “Call Salesforce REST API from Apex”

  1. Lokesh Avatar

    Nice article – saved my day

  2. Tapeshwar Kumar Avatar
    Tapeshwar Kumar

    Hello Sir,
    It is not working for me, can you please check this again.

  3. Anand Avatar

    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?

  4. nileshraj2 Avatar

    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.

    1. Raghu Avatar

      Hello Nilesh,
      we are also running into same issue, were you able to resolve ..?

  5. rodrigochiarato Avatar

    Great, tks

  6. Zsolt Avatar

    That is awesome!!!

Leave a Reply

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

Discover more from Jitendra Zaa

Subscribe now to keep reading and get access to the full archive.

Continue Reading