Wednesday, January 9, 2019

Salesforce rest api integration to update a record.

Today we will cover the topic Salesforce rest api integration by taking example of two Salesforce systems.

First, let's see when to use rest api as we have lot of other Salesforce api.

Rest api is a simple and power webservice based on restful principles and it uses rest resource and HTTP methods to expose functionalities. It supports both XML and JSON . Rest api has lightweight requests and responsive framework and it is good for mobile and web apps.

Let say I have two systems as SYSTEM A and another system as SYSTEM B.


What we will doing today is we will try to update a record in SYSTEM A manually and we will pass this record to SYSTEM B webservice, The webservice will than update the same record in SYSTEM B.

ACTIVITIES WE NEED TO DO IN SYSTEM B.

1)Create a connected app.
2)Rest api webservice to upadate record based on the requirement of SYSTEM A.

REST API WEBSERVICE FROM SYSTEM B:

@RestResource(urlMapping='/updateopportunityrecord/*')
   global with sharing class updateOpportunityClass {
     @httpput
      global Static string fetchAccount(){
      RestRequest req = RestContext.request;
      RestResponse res = Restcontext.response;
      string jsonString=req.requestBody.tostring();
      responseWrapper wResp=(responseWrapper) JSON.deserialize(jsonString,responseWrapper.class);   
      Opportunity obj=new Opportunity();
      obj=[select id,name,stagename,opptyExternalId__c from opportunity where opptyExternalId__c=:wResp.opptyExternalId];
      obj.stagename='Closed Won';
      update obj;
      return 'Success';
      }
       global class responseWrapper{
       global string opptyExternalId;
      }
   }

CONNECTED APP IMAGE FROM SYSTEM B:

Salesforce api

Note down the Consumer key, Consumer secret(We need to provide it SYSTEM A for authentication purpose along with username, password, security token of the user which SYSTEM A will be using for authentication).




ACTIVITIES WE NEED TO DO IN SYSTEM A.

1) Create a apex trigger.
2) Create an apex controller.
3) Create a remote site setting for the URL of System B.


APEX TRIGGER FROM SYSTEM A:

trigger opportunityMainTrigger on Opportunity (after update) {
    set<id> oppIdSet=new set<id>();
    for(opportunity opp:trigger.new){
        if(opp.StageName=='Closed Won'){
            oppIdSet.add(opp.id);
        }
     }
    if(oppIdSet.size() > 0){
        restApiToUpdateRecords.updateOppty(oppIdSet);
       }   
   }

APEX CONTROLLER FROM SYSTEM A :

public class restApiToUpdateRecords {
    private string cKey = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
    private string cSecret = 'XXXXXXXXXXXXXXXX';
    private string uName = 'XXXXXXXXXXXXXXXXXXXX';
    private string passwd = 'PASSWORD + SECURITY TOKEN';
    public class responseWrapper {
        public string id;
        public string access_token;
        public string instance_url;
    }
    public string getRequestToken() {
        string reqBody = 'grant_type=password&client_id=' + cKey + '&client_secret=' + cSecret + '&username=' + uName + '&password=' + passwd;
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        req.setBody(reqBody);
        req.setMethod('POST');
        req.setEndpoint('https://login.salesforce.com/services/oauth2/token');
        HttpResponse hresp = h.send(req);
        responseWrapper wResp = (responseWrapper) JSON.deserialize(hresp.getBody(), responseWrapper.class);
        system.debug('Instance url' + wResp.instance_url);
        system.debug('session id' + wResp.access_token);
        return wResp.access_token;
    }
    @future(callout = true)
    public static void updateOppty(set < id > oppIdSet) {
        for (Opportunity opp: [SELECT id, opptyExternalId__c from opportunity where id in: oppIdSet]) {
            wrapperParameter resWrap=new wrapperParameter();
            resWrap.opptyExternalId=opp.opptyExternalId__c;
            String accToken;
            string responseBody;
            string endPoint = 'https://ap5.salesforce.com/services/apexrest/updateopportunityrecord/';
            restApiToUpdateRecords obj = new restApiToUpdateRecords();
            accToken = obj.getRequestToken();
            system.debug('access token' + accToken);
            if (accToken != '') {
                Http h1 = new Http();
                HttpRequest req1 = new HttpRequest();
                req1.setHeader('Authorization', 'Bearer ' + accToken);
                req1.setHeader('Content-Type', 'application/json');
                req1.setBody(JSON.serialize(resWrap));
                req1.setMethod('PUT');
                req1.setEndpoint(endPoint);
                HttpResponse hresp1 = h1.send(req1);
                //listWrap=(list<resultWrapper>) JSON.deserialize(hresp1.getBody(),list<resultWrapper>.class);
            }
        }
    }
     public class wrapperParameter{
       public string opptyExternalId;
      }
}

REMOTE SITE STORED IN SYSTEM A:

Salesforce api

Now, let's update the opportunity record in SYSTEM A manually,


Salesforce rest api


Image from SYSTEM B,


Salesforce rest api


In this way we completed Salesforce rest api to update a record from one system to another by taking two Salesforce systems.

Please comment below if you have any doubts.

YOU CAN VISIT OTHER POST FROM OUR BLOG AS WELL,

Salesforce rest api integration to fetch single record (Click here)

Salesforce rest api integration to fetch list of records (Click here)

Salesforce rest api integration to create a record (Click here)


Salesforce rest api integration to delete a record (Click here)

Salesforce soap integration (Click here)

Salesforce rest api callouts (Click here)

11 comments:

  1. HI,
    Thank you for your post on SF app, and it was a great help.
    I have one doubt on a portion in
    public void getConList(), you have assigned Id to update, but not passed in the request?

    string accIdToupdate='0017F00001Xf1RO';

    Can you please explain where to pass 'accIdToupdate' in the request.

    Thank you,
    Thomas

    ReplyDelete
  2. can u please explain it is in sandbox a to sandbox b pass the values dynamically not fixed bu using id

    ReplyDelete
  3. How many maximum number of records we can update? using this rest api

    ReplyDelete
  4. Great post!
    Using this approach, we can only update single record.
    I want to update multiple records which are in JSON form using this approach(Using POST or PATCH method). How can we do that?

    ReplyDelete
    Replies
    1. I also want to update multiple records which are in JSON format.
      Can you please help?

      Delete
  5. Hi everybody, i want Know if this solution work with a externe org. i need to change field of a external application in real time. and the reverse

    ReplyDelete
  6. Hi - How are you setting the callback URL in the connected app? Also - which URL are you using for the remote site url? I'm not sure how to get values for either of these two things.

    Thanks

    ReplyDelete
  7. Getting External Id as null

    ReplyDelete