Wednesday, January 9, 2019

Salesforce rest api integration to create a record

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

First let's see when to use rest api as we have a 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.


Let's start,

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


ACTIVITIES WE NEED TO DO IN SYSTEM B.

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

REST API WEBSERVICE FROM SYSTEM B:

@RestResource(urlMapping='/createAccountRecord/*')

   global with sharing class createAccountRecord {

     @HttpPost

      global Static string createAccount(){

      RestRequest req = RestContext.request;

      RestResponse res = Restcontext.response;

      string jsonString=req.requestBody.tostring();

      responseWrapper wResp=(responseWrapper) JSON.deserialize(jsonString,responseWrapper.class);

      Account obj=new Account();

      obj.Name=wResp.name;

      Insert obj;

      return 'Success';

      }

      global class responseWrapper{

       global string name;

      }

   }

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 Accounttrigger on Account (after insert) {
    Set<id> accIdSet=new Set<id>();
    for(Account acc:trigger.new){
        if(acc.name!=Null){
            accIdSet.add(acc.id);
        }
    }
    if(accIdSet.size() > 0){
        callWebserviceClass.getConList(accIdSet);
    }
}

APEX CONTROLLER FROM SYSTEM A :


public class callWebserviceClass {
    private string cKey = 'XXXXXXXXXXXXXXXXXXXXXXXXXXX';
    private string cSecret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXX';
    private string uName = 'XXXXXXXXXXXXXXXXXXXXXXXXXXX';
    private string passwd = 'Password+SecurityToken';
   
   
    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 getConList(Set < id > accIdSet) {
        String accToken;
        string responseBody;
        string endPoint = 'https://ap5.salesforce.com/services/apexrest/createAccountRecord';
        callWebserviceClass obj = new callWebserviceClass();
        accToken = obj.getRequestToken();
        system.debug('access token' + accToken);
        if (accToken != '') {
            for (Account acc: [SELECT id,name from account where id in: accIdSet]) {
                system.debug('JSON' + JSON.serialize(acc));
                Http h1 = new Http();
                HttpRequest req1 = new HttpRequest();
                req1.setHeader('Authorization', 'Bearer ' + accToken);
                req1.setHeader('Content-Type', 'application/json');
                //req1.setHeader('accept','application/json');
                req1.setMethod('POST');
                req1.setBody(JSON.serialize(acc));
                req1.setEndpoint(endPoint);
                HttpResponse hresp1 = h1.send(req1);
                system.debug('hresp1' + hresp1);
            }
        }
    }
   
}



REMOTE SITE STORED IN SYSTEM A:

Salesforce api
Now, Let's try to create an account record in SYSTEM A manually, check the same record will be created in SYSTEM B as well.

Image from SYSTEM A,

salesforce rest api create record



Image from SYSTEM B,

salesforce rest api create record

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 update 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)


TAGS: Salesforce rest api integration between Salesforce and Salesforce,Salesforce api,Salesforce rest api,Salesforce rest api integration to create a record.

1 comment: