Showing posts with label web service. Show all posts
Showing posts with label web service. Show all posts

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. 

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