Sunday, December 11, 2016

Calling external REST service from Salesforce

Here is sample Trigger logic that sends updates in Salesforce to external systems by using REST

trigger TestRESTAPI on Account (after insert, after update) {

    HttpRequest req = new HttpRequest();
    HttpResponse res = new HttpResponse();
    Http http = new Http();
        
    string acctid = Trigger.new[0].Id;  
    string endpoint;   
    boolean userfilter;
    string token;

//Change the link below to appropriate external REST service            
    endpoint = 'https://azure-api.net/api/properties/v1.0/api/property/search?Limit=15'; 

//Method can be either POST or GET
    req.setMethod('POST');   
    req.setEndpoint(endpoint);    

//external REST service might require few parameters like key to be sent. These vary //depending on external REST service        
    req.setHeader('Ocp-Apim-Subscription-Key','4cf0db6dbffb4e5ba60eff6ddd41f3ec');
    req.setHeader('Authorization',token);
    req.setHeader('Content-Type','application/json; charset=utf-8');
    
//This is a simple example that is sending account id only but you can custom add 
// more fields
if (acctid != null && acctid != '')
       req.setBody(acctid);
       
    res = http.send(req);
    String responseStrng = res.getBody() ;
    system.debug(responseStrng);   
}

Depending on your business needs, you might use GET method in above example and you might receive required information from external system (output in the form of JSON). You might further need to process this JSON to use the output results 

I used the following app to process the JSON resposne for my rest API. Paste the response below and it will generate the class that you can use to deserialze the JSON later.

https://json2apex.herokuapp.com/

1 comment:

Develop a Visualforce Page in lightning style with SLDS

As many of customers are moving to lightning, we need to leverage SLDS framework to match the look and feel of visualforce page with the lat...