Tuesday, June 27, 2017

REST API and SOAP API in salesforce

1.What is SOAP and What is REST?

REST API

Representational State Transfer.
It is based URI:Uniform-Resource-Identifier
It works with GET,POST,PUT,DELETE
Works Over with HTTP and HTTPS


SOAP API

Simple Object Access Protocol.
It is based on Standard XML format
It is works with WSDL
Works Over with HTTP,HTTPS,SMPT,XMPP


2.Difference between REST API and SOAP API?
Ans :Varies on records that can be handled. Generally if we want to access less number of records we go for REST API.

3.What is WSDL?
A WSDL is an XML Document which contains a standardized description of how to communicate using webservice.

4.What are the different type of WSDL'S?
Ans:
Enterprise WSDL
Partner WSDL
Apex WSDL
Metadata WSDL
Tooling WSDL
Delegated Atuntection WSDL

5.Difference between Enterprise WSDL and Partner WSDL?
Ans:
Enterprise WSDL:
It is used for building client applications for a single salesforce organization.
Customers who use enterprise WSDL document must download and re-consume it when ever their organization makes a change to its custom objects or fields or when ever they want to use a different version of the API.
Partner WSDL:
It is used for building client applications for multiple organizations.
The partner WSDL documention only needs to be downloaded consumed once per version of the API.

6.How can you expose an apex class as a REST web service in salesforce?
Ans - An apex class can be exposed as REST web service by using keyword '@RestResource'

7.How to fetch data from another Salesforce instance using API?
Ans :Use the Force.com Web Services API or Bulk API to transfer data We this this is a great job for the Bulk API.

8.How to call Apex method from a Custom Button?
Ans :An Apex callout enables you to tightly integrate your Apex with an external service by making a call to an external Web service or sending a HTTP request from Apex code and then receiving the response.
Apex provides integration with Web services that utilize SOAP and WSDL, or HTTP services (RESTful services).

9.What is the use of Chatter REST API?
The Chatter API (also called Chatter REST API) lets you access Chatter information via an optimized REST-based API accessible from any platform. Developers can now build social applications for mobile devices, or highly interactive websites, quickly and efficiently.

10.How to fetch data from another Salesforce instance using API?
Answer: Use the FORCE.COM WEB SERVICES API or BULK API to transfer data We this this is a great job for the Bulk API.

11.What are callouts and call ins?
Making a request to an external system from salsforce is callout.

Getting requests from an external system is a call in.

12.How many callouts to external service can be made in a single apex transaction?
Ans - A total of 10 callouts are allowed in a single apex transaction.

13.What is the maximum allowed time limit while making a callout to external service in apex?
Ans - maximum of 120 second time limit is enforced while making callout to external service

14.What is the default timeout period while calling webservice from Apex.
Ans : 10 sec.

15.can we define custom time out for each call out?
Ans :
A custom time time can be defined for each callout.
the minimum time is 1 millisecond and maximum is 120,000 milli seconds.

16.How to increase timeout while calling web service from Apex ?
Ans :
docSample.DocSamplePort stub = new docSample.DocSamplePort();
stub.timeout_x = 2000; // timeout in milliseconds

17.What is the use of JSON?

18. Salesforce to Salesforce Example
Ans :

What is Web Service and What are different types of web services?

Web Service is can be defined by following ways:
  • Is a client server application or application component for communication.
  • Method of communication between two devices over network.
  • Is a software system for interoperable machine to machine communication.
  • Is a collection of standards or protocols for exchanging information between two devices or application.

Let's understand it by the figure given below:



As you can see in the figure, java, .net or PHP applications can communicate with other applications through web service over the network. For example, java application can interact with Java, .Net and PHP applications. So web service is a language independent way of communication.

Types of Web Services
There are mainly two types of web services.
  1. SOAP web services.
  2. RESTful web services.



SOAP Web Services

SOAP stands for Simple Object Access Protocol. It is a XML-based protocol for accessing web services. SOAP is a W3C recommendation for communication between two applications.


SOAP is XML based protocol. It is platform independent and language independent. By using SOAP, you will be able to interact with other programming language applications.


Advantages of Soap Web Services

WS Security: SOAP defines its own security known as WS Security.

Language and Platform independent: SOAP web services can be written in any programming language and executed in any platform.

Disadvantages of Soap Web Services
Slow: SOAP uses XML format that must be parsed to be read. It defines many standards that must be followed while developing the SOAP applications. So it is slow and consumes more bandwidth and resource.

WSDL dependent: SOAP uses WSDL and doesn't have any other mechanism to discover the service.

RESTful Web Services

REST stands for Representational State Transfer. REST is an architectural style not a protocol.

Advantages of RESTful Web Services

Fast: RESTful Web Services are fast because there is no strict specification like SOAP. It consumes less bandwidth and resource.

Language and Platform independent: RESTful web services can be written in any programming language and executed in any platform.

Can use SOAP: RESTful web services can use SOAP web services as the implementation.

Permits different data format: RESTful web service permits different data format such as Plain Text, HTML, XML and JSON.


SOAP vs REST Web Services

S.No
SOAP
REST
1
SOAP is a protocol.
REST is an architectural style.
2
SOAP stands for Simple Object Access Protocol.
REST stands for REpresentational State Transfer.
3
SOAP can't use REST because it is a protocol.
REST can use SOAP web services because it is a concept and can use any protocol like HTTP, SOAP.
4
SOAP uses services interfaces to expose the business logic.
REST uses URI to expose business logic.
5
SOAP defines standards to be strictly followed.
REST does not define too much standards like SOAP.
6
SOAP defines standards to be strictly followed.
REST does not define too much standards like SOAP.
7
SOAP requires more bandwidth and resource than REST.
REST requires less bandwidth and resource than SOAP.
8
SOAP defines its own security.
RESTful web services inherits security measures from the underlying transport.
9
SOAP permits XML data format only.
REST permits different data format such as Plain text, HTML, XML, JSON etc.
10
SOAP is less preferred than REST.
REST more preferred than SOAP.


Google drive Integration with REST API:













Page:


<apex:page controller="cGoogleAppAuthenticationWithSalesforce">
    <apex:form >
      <apex:pageBlock >
       <apex:commandButton value="Authenticate" action="{!DriveAuth}"/>
          <apex:pageBlockTable value="{!FileIdAndNamemapfortheaccount}" var="f">
           <apex:column headerValue="Google files">
            <apex:outputLink value="https://drive.google.com/open?id={!f}" target="_blank">{!FileIdAndNamemapfortheaccount[f]}</apex:outputLink>
           </apex:column>
          </apex:pageBlockTable>
      </apex:pageBlock>
    </apex:form>
</apex:page>

Helper Class:

global class cAuthURIForApiReq {
    global string AuthenticationURI ='';
    public cAuthURIForApiReq(string Clientkey,string redirect_uri){
        string key = EncodingUtil.urlEncode(Clientkey, 'UTF-8');
        string uri = EncodingUtil.urlEncode(redirect_uri, 'UTF-8');
        string authuri = 'https://accounts.google.com/o/oauth2/auth?'+
                             'client_id='+key+
                             '&response_type=code'+
            '&scope=https://www.googleapis.com/auth/drive'+
            '&redirect_uri='+uri+
            '&state=security_token%3D138r5719ru3e1%26url%3Dhttps://oa2cb.example.com/myHome&'+
                             '&login_hint=venkat81215@gmail.com&'+
                             'access_type=offline';
        AuthenticationURI = authuri;
    }
}

Controller:
public class cGoogleAppAuthenticationWithSalesforce {
        private string key = '1061673298812-gf8h00foeiij02m3bksae9f6jhac4j10.apps.googleusercontent.com';
        private string secret = 'm5G6cbvLym4NVKYz7W-fX8pJ';
        private string redirect_uri ='https://'+System.URL.getSalesforceBaseUrl().getHost()+'/apex/GoogleDriveINteg';
        private string codemeniaidentificationToken;
        private string access_token;
        private list<string> FileLst;
    public map<string,string> FileIdAndNamemapfortheaccount{get;set;}
    
    public cGoogleAppAuthenticationWithSalesforce(){
          codemeniaidentificationToken = ApexPages.currentPage().getParameters().get('code');
        if(codemeniaidentificationToken !='' && codemeniaidentificationToken !=null){
            accesstoken();
        }
        FileLst =new list<string>();
        FileIdAndNamemapfortheaccount = new map<string,string>();
    }
    public PageReference DriveAuth(){
        PageReference pg = new PageReference(new cAuthURIForApiReq(key,redirect_uri).AuthenticationURI);
        return pg;
    }
    Public void accesstoken(){
        //getting access token from google
        HttpRequest req = new HttpRequest();
        req.setMethod('POST');
        req.setEndpoint('https://accounts.google.com/o/oauth2/token');
        req.setHeader('Content-type','application/x-www-form-urlencoded');
        String messageBody = 'code='+codemeniaidentificationToken+'&client_id='+key+'&client_secret='+secret+'&redirect_uri='+redirect_uri+'&grant_type=authorization_code';
        req.setHeader('Content-lenth',String.valueOf(messageBody.length()));
        req.setBody(messageBody);
        req.setTimeout(60*1000);
        
        Http h = new Http();
        HttpResponse res = h.send(req);
        JSONParser parser = JSON.createParser(res.getBody());
        while(parser.nextToken()!=null)
        {
            if((parser.getCurrentToken() == JSONToken.FIELD_NAME)&&(parser.getText() == 'access_token'))
            {
                parser.nextToken();
                access_token = parser.getText();
                break;
            }
        }
        if(access_token != ''&& access_token !=null){
            ListFiles();
        }
    }
    public pagereference ListFiles(){
        Google_drive__c g = new Google_drive__c();
        g=[select name,Folder_ID__c from Google_drive__c where Name = 'Main'];
        string Folderid = g.Folder_ID__c;
        HttpRequest req1 = new HttpRequest();
        req1.setMethod('GET');
        req1.setEndpoint('https://www.googleapis.com/drive/v2/files/'+Folderid+'/children');
        req1.setHeader('contant-type','application/x-www-form-urlencoded');
        req1.setHeader('content-length','0');
        req1.setHeader('authorization','Bearer'+''+access_token);
        req1.setTimeout(60*1000);
        Http h2 = new Http();
        HttpResponse res1 = h2.send(req1);
        JsonParser parserd = JSON.createParser(res1.getBody());
        while (parserd.nextToken()!=null){
            if((parserd.getCurrentToken()==JSONToken.FIELD_NAME)&&(parserd.getText()=='id')){
                parserd.nextToken();
            FileLst.add(parserd.getText());
        }
    }
       map<string,string> FileIdAndNamemap = Fileproperties();
     // map<string,string> FileIdAndNamemap;
        for(string s : Filelst){
            FileIdAndNamemapfortheaccount.put(s,FileIdAndNamemap.get(s));
        }
        return null;
    }
    public map<string,string> Fileproperties(){
        map<string,string> Filepropertiesdetails = new map<string,string>();
         HttpRequest req2 = new HttpRequest();
        req2.setMethod('GET');
        req2.setEndpoint('https://www.googleapis.com/drive/v3/files');//'+Folderid+'/children');
        req2.setHeader('contant-type','application/x-www-form-urlencoded');
        req2.setHeader('content-length','0');
        req2.setHeader('authorization','Bearer'+''+access_token);
        req2.setTimeout(60*1000);
        Http h3 = new Http();
        HttpResponse res1s = h3.send(req2);
        JsonParser parserdr = JSON.createParser(res1s.getBody());
        while (parserdr.nextToken()!=null){
            string filename = '';
            string fileid = '';
            if((parserdr.getCurrentToken()==JSONToken.FIELD_NAME)){
                if((parserdr.getText()=='id')){
                    parserdr.nextToken();
                    fileid = parserdr.getText();
                }
                parserdr.nextToken();
                if((parserdr.getText()=='name')){
                     parserdr.nextToken();
                    filename = parserdr.getText();
                } 
            Filepropertiesdetails.put(fileid,filename);
        }
    }
        return Filepropertiesdetails;
    }
}

How to do Integration between two different organizations in salesforce Using REST API and REST Web Service and Apex Web Service?

For this post, I will offer a simple explanation of the complex, yet interesting areas essential for the complete understanding of Salesforce Integration’s capabilities. The business scenario quoted, along with the working code samples, will be a good starting point for entering into the world of non-declarative ways for integrating with Salesforce. Here’s what I’ll cover:

Understanding authentication and its prerequisites
OAuth authentication flows for REST API calls
Apex triggers and callouts
REST API, REST web services, and Apex web services

1) Authentication and Its Prerequisites
Authenticating a client application is the first and foremost step while building an interface.

The authentication method depends on your chosen call type (REST or SOAP). Let’s see how to do it using REST.

Before moving any further, let’s frame a business scenario. We’ll use two Salesforce instances that exchange Account details. When a new Account is created in one org, it will flow down to the other Salesforce org, and in return the source org will get the Salesforce Record ID of the created record. These two orgs are:

Source Salesforce org (used for callout) – Source
Target Salesforce org (used for receiving requests) – Target

Following our business scenario, we can say that authentication is a collection of the following sub-steps. Though actual authentication calls a trigger from the Apex code, consider these steps as the prerequisites because without them being completed first, the authentication calls won’t work.

Choosing OAuth Endpoint (to be invoked from Source org)
Choosing OAuth Authentication flow (to be used by Source org)

Remote Site Setting in Source Org.




Connected App enables Salesforce to recognize and authenticate an external application as a new entry point. OAuth is used for this authentication. We need to create a Connected App record in Target org. Below is an illustration.

Connected App in Target Org.




callback url should be specified in the remote site setting
Once after saving the record the client id and clientSecret are generated.

Create a Trigger to make an asynchronous call from source org to target org

Trigger on account Object:


?
1
2
3
4
5
6
trigger SendAccount on Account(after insert)
{
for(Account a : Trigger.new){
SendAccountFromSource.createAccount(a.Name, a.Id);
}
}

Apex Class to make a callout :

Replace the clientid,secret,username and password's of your org.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
public class SendAccountFromSource {
private final String clientId = 'Clent Id from App';
private final String clientSecret = 'clientSecretfrom app';
private final String username = 'username';
private final String password = 'passwordwithsecuritytoken';
public class deserializeResponse
{
public String id;
public String access_token;
}
public String ReturnAccessToken (SendAccountFromSource acount)
{
String reqbody = 'grant_type=password&client_id='+clientId+'&client_secret='+clientSecret+'&username='+username+'&password='+password;
Http h = new Http();
HttpRequest req = new HttpRequest();
req.setBody(reqbody);
req.setMethod('POST');
HttpResponse res = h.send(req);
deserializeResponse resp1 = (deserializeResponse)JSON.deserialize(res.getbody(),deserializeResponse.class);
return resp1.access_token;
}
@future(callout=true)
public static void createAccount(String accName, String accId)
{
SendAccountFromSource acount = new SendAccountFromSource();
String accessToken = acount.ReturnAccessToken (acount);
if(accessToken != null)
{
String jsonstr = '{"Name" : "' + accName + '"}';
Http h2 = new Http();
HttpRequest req1 = new HttpRequest();
req1.setHeader('Authorization','Bearer ' + accessToken);
req1.setHeader('Content-Type','application/json');
req1.setHeader('accept','application/json');
req1.setBody(jsonstr);
req1.setMethod('POST');
req1.setEndpoint(endPoint);
HttpResponse res1 = h2.send(req1);
deserializeResponse resp2 = (deserializeResponse)JSON.deserialize(res1.getbody(),deserializeResponse.class);
Account a = [SELECT Id FROM Account WHERE Id = :accId];
a.externalId__c = resp2.id;
update a;
}
}
}
Explanation –
1 Setting the REST API resource to create an Account (sObject)
2 Creating the JSON string to be sent as the input
3 Setting the Header to include the access token
4 Querying the Account record in Source Org so it can be updated
5 Setting the custom foreign key field on Account in Source Org with the extracted Account ID from the response.

Till here we have worked with Rest API.

REST Webservices

When working with rest webservices we need to change the code in the createAccount method in SendAccountFromSource class . Which looks like
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
if(accessToken != null)
{
String jsonstr = '{"AccName" : "' + accName + '"}';
Http h2 = new Http();
HttpRequest req1 = new HttpRequest();
req1.setHeader('Authorization','Bearer ' + accessToken);
req1.setHeader('Content-Type','application/json');
req1.setHeader('accept','application/json');
req1.setBody(jsonstr);
req1.setMethod('POST');
req1.setEndpoint(endPoint);
HttpResponse res1 = h2.send(req1);
String trimmedResponse = res1.getBody().unescapeCsv().remove('\\');
deserializeResponse resp2 = (deserializeResponse)JSON.deserialize(trimmedResponse, deserializeResponse.class);
Account a = [SELECT Id FROM Account WHERE Id = :accId];
a.externalId__c= resp2.id;
update a;
}

Here in this example we need to change the endpoint url that is pointing to createAccount class in the target org. Create a new rest web service class createAccount in target org.


?
1
2
3
4
5
6
7
8
9
10
11
12
13
@RestResource(urlMapping='/v1/createAccount/*')
global with sharing class createAccount
{
@HttpPost
global static String createAccount(String AccName)
{
Account a = new Account();
a.Name = AccName;
insert a;
String returnResponse = JSON.serialize(a);
return returnResponse;
}
}
Explanation –
1 Exposing the web service using the @RestResource annotation
2 Exposing method as REST resource to be called when HTTP Post request is made to this web service
3 Creating a new Account in Target org and setting the name as passed from Source org
4 Serializing the response (Account details) before sending
5 Sending the response.

Apex Web Service

Finally, the third option is the Apex Web Service that uses SOAP to handle integration. The class written at the target needs to be exposed as a global Web Service.


?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
global class CreateAccountApexWS
{
global class sAccount
{
webservice String name;
}
webservice static String createAccount(sAccount sAcct)
{
Account acct = new Account();
acct.Name = sAcct.name;
insert acct;
String returnResponse = JSON.serialize(acct);
return returnResponse;
}
}
Explanation –
1 Creating a Global class that can be accessed from anywhere
2 Using the webservice keyword to expose class variable as an input to the web service
3 Using the webservice keyword to expose the class method as a custom SOAP Web Service 

1 comment:

  1. Very Good Post! Thank you so much for sharing this good post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
    Visit us: Java Online Training Hyderabad
    Visit us: Java Training

    ReplyDelete