anusha(salesforce developer)

Monday, 1 August 2016

Apex Webservices and integration Concept

alesforce Rest Services are a powerful as well as convenient way to expose web services from a organization. It uses simple HTTP methods like GET , POST etc. to access and manipulate data. The data exchange format is in the form of JSON generally. 

The following is a sample apex class which illustrates the POST method to post details and GET method to retrieve details from an outside application.


Sample Rest Apex Class:


/*  
   The urlMapping acts as an accessible endpoint and adds to the full URL used to call this webservice from an external point  
   For example, something like "https://ap1.salesforce.com/services/apexrest/Account"  
 */  
 @RestResource(urlMapping='/Account/*')  
 global with sharing class callAccount {  
  /*  
   HttpPost method is used to capture a HttpPost request has been sent to our rest apex class.  
   Used to retrieve data coming in the request body and performing corressponding actions  
  */  
  @HttpPost  
   global static String doPost() {  
     /*  
       RestContext Class - Allows us to access the RestRequest and RestResponse objects in your Apex REST methods.   
       RestRequest class - Allows us to pass request data into our Apex RESTful Web service method.  
       RestResponse class - Allows us to pass or send back response data from our Apex RESTful web service method  
     */  
     //Returns the RestRequest object for our Apex REST method.  
     RestRequest request = RestContext.request;  
     //Returns the RestResponse for our Apex REST method.  
     RestResponse response = RestContext.response;  
     //Access the request body with input data coming in the JSON format  
     String jSONRequestBody=request.requestBody.toString().trim();  
     //Deserializes the input JSON string into an Account object  
     Account accObj = (Account)JSON.deserializeStrict(jSONRequestBody,Account.class);  
     //insert the account object and return the account ID   
     insert accObj;  
     return accObj.Id;  
   }  
   /*  
   HttpGet method is used to capture a HttpGet request has been sent to our rest apex class.  
   Used to request data on the basis of a parameter sent in the URL  
  */  
  @HttpGet  
   global static Account doGet() {  
   /*  
       RestContext Class - Allows us to access the RestRequest and RestResponse objects in your Apex REST methods.   
       RestRequest class - Allows us to pass request data into our Apex RESTful Web service method.  
       RestReponse class - Allows us to pass or send back response data from our Apex RESTful web service method  
     */  
     //Returns the RestRequest object for our Apex REST method.  
     RestRequest request = RestContext.request;  
     //Returns the RestResponse for our Apex REST method.  
     RestResponse response = RestContext.response;  
     //Retrieve the parameter sent in the URL  
     String accountId = request.requestURI.substring(request.requestURI.lastIndexOf('/')+1);  
     //query the account on the basis of id sent and return the record  
     Account acc= [SELECT Id, Name, Phone, Website FROM Account WHERE Id = :accountId];  
     return acc;  
   }  
 }  



Call the Rest  WebService
Set up in salesforce org 
1.        Go to Setup, click Create | Apps, and in the Connected Apps section, click New to create a new Connected App.

2.        Enter a Connected App name.
3.        Enter the contact email, as well as any other information appropriate to your application.
4.        Under Section ‘OAuth Settings’, mark the enable OAuth Settings checkbox and enter a Callback URL for example:  https://ap1.salesforce.com/services/oauth2/token


5.        Enter an OAuth scope. Select :




a.        Perform requests on your behalf at any time (refresh_token)
b.        Provide access to your data via the Web (web)
c.        Access and manage your data (API)
6.        Click Save. The Consumer Key is created and displayed, and a Consumer Secret is created (click the link to reveal it).


Call webservice using cURL

To call the rest apex class from outside salesforce, we either need to set up cURL or a client/system capable of making http request. Here is an example showing how to use cURL to call the REST service. 

FIRST we need to download the curl executable file (SSL enabled), preferably from http://curl.haxx.se/download.html (corresponding to the OS and the version) . cURL has some user friendly commands to call the rest service with OAuth authentication.

1.       Command to receive the authorization token :



 curl --form client_id=[Your client Id] --form client_secret=[Your client secret] --form grant_type=password --form username=[Your Username] --form password=[Your Password+Your Security Token] -k https://[Your salesforce instance].salesforce.com/services/oauth2/token  

For example :
curl --form client_id=3MVG9_7ddP9KqTzd_3A4dh9sZ4fpxuyOxHUCQ.GRu6EY7ETY2xFAGBrkv8BO17HmOR_X47cahreAbO7WjQgLd --form client_secret=2607521253690956513 --form grant_type=password --form username=test@gmail.com --form password=password1$RjzaF3v6HahniNEWpxUlUIoG -k https://cs10.salesforce.com/services/oauth2/token  


2.        Use cURL to call the webservice
a.       Command to GET account details using the authorization token received from the above command :

 curl -X GET https://[Your salesforce instance].salesforce.com/services/apexrest/ [URI Mapping] /[account Id] -H "Authorization: OAuth [Your authorization token]" -k  

For example : 
 curl -X GET https://ap1.salesforce.com/services/apexrest/Account/0019000000Nah1a -H "Authorization: OAuth 00D90000000kIy777RYAQGVLW60UaT.yKMONqfjztdq1__6SGL70qOVFtwvYwj_4oykw7_QgKOTbl6jhZDAaYgtTW0ZR9THihS29MwPHAEuyxFbM" -k   


b.      Command to POST and create account using the authorization token received from the above command :

Suppose we use a JSON file with the following input:
  
 {  
             “Name”:”testaccount”,  
             “Phone”:”1234567890”  
 }  


 curl https://[Your salesforce instance].salesforce.com/services/apexrest/ [URI Mapping] /[account Id] -H "Authorization: OAuth [Your authorization token]" -H "Content-Type: application/json" -d @[Name of JSON file] -k  

For Example : 
curl https://ap1.salesforce.com/services/apexrest/Account/ -H "Authorization:OAuth 00D90000000kIy777RYAQGVLW60UaT.yKMONqfjztdq1__6SGL70qOVFtwvYwj_4oykw7_QgKOTbl6jhZDAaYgtTW0ZR9THihS29MwPHAEuyxFbM" -H "Content-Type: application/json" -d @account.json -k  

This demo demonstrates how to create/query account using simple HTTP calls. This example can be extended further to accomplish more complex tasks.

Further JSON support makes REST Webservices excellent way to integrate with External Systems including legacy systems.  REST Webservices can be used to integrate two different Salesforce Org and let them talk seamlessly. In next part we will be covering 

1 comment: