Free computer code on screen

Invoke Salesforce REST API from Apex

“In the previous post, we discussed how Visualforce can be utilized to invoke Salesforce’s REST API. In this concise article, I will provide a brief code snippet to illustrate how Apex can be employed to make calls to Salesforce’s REST API.

The initial and crucial step is to include your Salesforce instance URL in the Remote Site Settings. Once this configuration is complete, you can use the following sample Apex code to make calls to Salesforce’s REST API.

In this example, I am using the API to retrieve metadata information about Salesforce objects; however, you can replace this with any supported REST API provided by 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.setMethod('GET');  
httpRequest.setHeader('Authorization', 'OAuth ' + UserInfo.getSessionId());       
httpRequest.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionID());
httpRequest.setEndpoint(restAPIURL); 
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 );

An essential element in the code above is how the session Id is employed as a value in both the OAuth and Bearer headers.