Thursday, February 2, 2017

Call Salesforce REST API from Apex

Nothing new but just below example helps make call to Salesforce REST API from Apex. If you need to know Org limits at run time, most them are available via Limits call, but some are available via rest api at : /services/data/v37.0/limits (e.g. daily async limits, email or bulk email limits, etc.)  and it is easy to get those information from workbench.developerforce.com, however if you need to add this to the code, below is the code:


Add your Org URL to remote site setting
Note: if you don't know, then either you can look at browser or via below call:
System.debug( URL.getSalesforceBaseUrl().toExternalForm() );


Run Anonymous block below, which is broken down into three pieces
1. Get the base URL
2. Get Auth Token
3. Actual HTTP Request

 /* 1. get base URL */  
 public static String getSalesforceInstanceUrl() {  
       return URL.getSalesforceBaseUrl().toExternalForm();
 }  
   
 public static String getRestResponse(String url) {   
       HttpRequest httpRequest = new HttpRequest();  
       httpRequest.setEndpoint(url);  
       httpRequest.setMethod('GET');  
       /* 2. set the auth token */
       httpRequest.setHeader('Authorization', 'OAuth ' + UserInfo.getSessionId());        
       httpRequest.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionID());  
       try {  
             Http http = new Http();  
             /* initiate the actual call */  
             HttpResponse httpResponse = http.send(httpRequest);  
             if (httpResponse.getStatusCode() == 200 ) {  
                   return 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;  
       }  
       return null;  
 }  
   
 System.debug(' -- limit method code block -- : start ');  
 String baseUrl = getSalesforceInstanceUrl();  
 System.debug(' -- baseUrl-- : ' + baseUrl );  
 String limitsUrl = baseUrl + '/services/data/v37.0/limits';  
 System.debug(' -- limitsUrl-- : ' + limitsUrl );  
 String response = getRestResponse(limitsUrl);  
 System.debug(' -- response-- : ' + response );