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.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 );
Key aspect in above code is how session Id is used as a value in OAuth and Bearer headers.
Leave a Reply