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/

Exposing Apex functionality through Rest Service

Here is a quick demo on exposing Apex Class functionality to external Systems through REST service.

Step 1: Create a apex class with all the fields required in REST request.

global class LeadInfoParser {
    global String LastName{get;set;}
    global String FirstName{get;set;}
    global String Company{get;set;}
    global String email{get;set;}
    global String Phone{get;set;}
    global String LeadStatus{get;set;}    

}

Step 2:To declare a class as a custom endpoint, you only need to annotate a global class with “@RestResource” and define the name of the endpoint.
In the below example, REST Service endpoint will be 
https://salesforcehostname/services/apexrest/LeadService

@RestResource(urlMapping='/LeadService/*')
global without sharing class LeadService {
    @HttpPost
    global static String createLead(LeadInfoParser leadrec){
        Lead leadObj = new Lead();
        leadObj.FirstName =leadrec.FirstName;
        leadObj.LastName=leadrec.LastName; 
        leadObj.Phone=leadrec.Phone;
        leadObj.email=leadrec.email; 
        leadObj.Company = leadrec.Company;
        leadObj.Status = leadrec.LeadStatus;             
      
        Database.saveResult saveResult = database.insert(leadObj,false);
        if(saveResult.isSuccess()){
            System.debug('Record Id:'+saveResult.getId());
        }
        else{
            System.debug('saveResult:'+saveResult.getErrors());
        }
        //Response
        JSONGenerator gen=JSON.createGenerator(true);     
        gen.writeStartObject();
        gen.writeStringField('message','Lead record is created Successfully');
        gen.writeEndObject();     
        String responseString= gen.getAsString();
        return responseString;
    }

}

REST Service is now ready with these two simple steps. We can quickly test this REST service using workbench.developerforce.com.

Request Body:
{"leadrec":{
   "FirstName":"Laxman",
   "LastName":"Vattam",
   "Company":"Google",
   "LeadStatus":"Open",
   "email":"laxmanVattam@gmail.com",
   "Phone":"+1123456"

 }




A lead should have been created successfully in Salesforce. REST service is now ready for external systems to call.
We can use @HttpGet similar to @HttpPost example above.

Developers can tailor the REST API to suit the business needs of their application. An endpoint can be defined with an Apex Class using the @RestResource annotation, and the method annotations allow the endpoint to behave specifically for creating, updating, deleting and querying data within the instance. 

Must have Chrome extensions for Salesforce Developers/Admins

Salesforce Change Set Helper:
We often spend many hours to add components to changeset. This Chrome extension will help you with so may features that will drastically bring down the hours to build it:
 - Includes the last modified date and user and api name for each item.
 - Automatically ordered by most recent modified first
 - Filter/Search/Order by any field.
 - Sets all pages to show the 1000 rows.  If more than 1000 items in a page, asks if you want to continue to retrieve more. 

 - View and Search on items in the change set.  This allows you to see the whole change set and search to make removing much easier.

Salesforce Logins by Synebo
As admin/developer, we often need to login to multiple sandboxes every day. It is tiresome to enter passwords each time you login to various sandboxes. If you use tools like data loader, it is additional overhead to maintain list of security tokens for various sandboxes. This chrome extension lets you login to Salesforce Sandboxes/Prod with just one click and also provide options to save security tokens for various sandboxes.

When we open multiple sandboxes at the same time, this extension displays coloured cloud icon to differentiate various sandboxes

Salesforce ORGanizer:
Above two extensions are combined into this one extension. It has more capabilities like setting
default page to be launched on login as well as launching other pages thru this extension.



We often need to verify the API field name for fields on detail pages. This extension will help you quickly find the API names of the fields. This works only in classic.
               
This extension helps you to search your code for any keywords/fields with out opening other tools like eclipse.


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...