Call Salesforce REST API from Apex

Author posted by Jitendra on Posted on under category Categories Salesforce and tagged as Tags , with Leave a comment on Call Salesforce REST API from Apex

Use Apex to call Salesforce REST API with sample source code

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

Leave a Reply