Search This Blog

Sunday, March 13, 2016

Rest api Integration Example

In this example I am fetching the data from one salesforce instance into other salesforce instance.
Steps:
Step 1: Create a rest resource in one salesforce instance from which we need to retrieve data.Assume this instance as destination.
The sample rest resource class will be like this.
Apex Class:
@RestResource(urlMapping='/displayAccounts/*')
global class AccountRESTController {
    @HttpGet
    global static LIST<Account> getAccounts() {
        List <Account> accountList;
        try {
            accountList = [select id,name from Account limit 5];
            return accountList;
        }
        catch(Exception e) {
           system.debug('errror'+e.getMessage());
        }
        return accountList;
    }
}

In order to access this rest resource from outside, the url or endpoint will be like this "https://ap1.salesforce.com/services/apexrest/displayAccounts" .It means the url of this resource will be salesforcebaseurl, followed by services, followed by apexrest ,followed by keyword used in url mapping.
Step 2:  Create one connected app in destination org where rest resource class is created for authentication purpose.
Go to setup --> create --> apps --> Go to Connected Apps section and click "New" button.
Fill the mandatory fields like connected app Name,API Name,Contact Email fields and select "Enable OAuth Settings checkbox in API(Enable OAuth Settings) Section.
Provide the callback url and the OAuth Scope and then click save button and then continue.
Now the connected app is created as shown in the image below.

The consumer Key and Consumer Secret are generated Which are later used in authentication.
Step 3: Now create one apex class in source instance to fetch data from destination instance.
Apex Class:
public class DataController {
    public List<Account> accountList {get;set;}
    public void retrieveData() {
        HttpRequest req = new HttpRequest();
        req.setEndpoint('https://ap1.salesforce.com/services/oauth2/token');
        req.setMethod('GET');
        req.setBody('grant_type=password&client_id=clientID&client_secret=secretkey&username=username&password=password');
        Http http = new Http();
        HTTPResponse res = http.send(req);
        String resBody = res.getBody();
        Map<String,Object> jsonMap = (Map<String,Object>)JSON.deserializeUntyped(resbody);
        system.debug('jsonMapjsonMap'+jsonMap );
        String accessToken ='';
        if(jsonMap != null && jsonMap.containsKey('access_token')) {
            accessToken = String.valueOf(jsonMap.get('access_token'));
            system.debug('accessTokenaccessToken'+accessToken);
        }
        System.debug('initial response to get token'+res.getBody());
        if(accessToken != null) {
            HttpRequest req1 = new HttpRequest();
            req1.setEndpoint('https://ap1.salesforce.com/services/apexrest/displayAccounts');
            req1.setMethod('GET');
            req1.setHeader('Authorization','OAuth '+accessToken);
            Http http1 = new Http();
            HTTPResponse res1 = http1.send(req1);
            String resBody1 = res1.getBody();
            accountList = (List<Account>) JSON.deserialize(resBody1, List<Account>.class);
            system.debug('accountListaccountList '+accountList );
        }
    }
}
In the above class replace clientID with consumer key and secretkey with Consumer Secret generated in connected App.
Also replace  username and password with salesforce destination instance username and password.
Note :We need to add the destination endpoint url in remote site settings of Source instance as shown in image below.

Step 4: Now create one Visualforce page in source instance to display fetched data from destination instance.
Visualforce Page:
<apex:page controller="DataController">
    <apex:form >
        <apex:commandButton value="Retrieve Data from SFDC" action="{!retrieveData}"/>
        <apex:pageBlock>
            <apex:pageblockTable value="{!accountList}" var ="acc">
                <apex:column value="{!acc.name}"/>
                <apex:column value="{!acc.Id}"/>
            </apex:pageblockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>
Output:


Note: Please let me know if you have any doubts...Enjoy Coding.

No comments:

Post a Comment