Salesforce REST Webservices - Part I


Salesforce 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 How to use Rest Webservices to integrate two different Salesforce Orgs. 




23 comments:

  1. Thanks for your great information, the contents are quiet interesting.I will be waiting for your next post. website development company

    ReplyDelete
  2. A web development company can offer your business not only web development services but, also a range of other services which can take your company to the very top. However, most importantly, these companies can offer you with a team of highly skilled web designers who can design the very best page for your company.

    ReplyDelete
  3. A web development company can offer your business not only web development services but, also a range of other services which can take your company to the very top. However, most importantly, these companies can offer you with a team of highly skilled web designers who can design the very best page for your company.

    ReplyDelete
  4. I really appreciate people who share their thoughts and knowledge with everyone. Thanks for sharing your blog.

    PHP web development company in Mumbai

    ReplyDelete
  5. Wonderful post, thanks for sharing. Attrait Solutions is the top web development company mumbai. It provide many services like development, SEO, SMO services and many more.

    ReplyDelete
  6. I was looking for Web Design Nagpur Jobs came across this blog . Good information provided.Thanks for sharing with us.

    ReplyDelete
  7. Thanks for the article. It was really helpful and cut my turn around time.

    ReplyDelete
  8. How to use Rest Webservices to integrate two different Salesforce Orgs.
    Please pot this article.

    ReplyDelete
  9. Glad to read your post...Thanks for sharing such a nice information, its beneficial for me. I have you bookmarked to check out new stuff you post. Keep sharingWebsite Design Companies Bangalore | Web Designing Companies Bangalore

    ReplyDelete
  10. Thank you for sharing the useful information...I have a getting the lots of information...
    Website Development in Bangalore | Website Designing Bangalore

    ReplyDelete
  11. This comment has been removed by the author.

    ReplyDelete
  12. Hi all,
    I am unable to Pass more than 32 inpust parameter to @httpPost Please Help Me,Thanks in Advance
    @RestResource(urlMapping='/Students/*')
    global with sharing class Studnets {



    @HttpPost
    global static String doPost(Integer Max,String ConcurrentAsyncGetReportInstances,String ConcurrentSyncReportRuns,Integer Max1,
    Integer Remaining,Integer Remaining1,String DailApiRequest,Integer DAPIRemaining,Integer DAPiMax,String Ant,Integer AntMax,
    Integer AntRemaining,String App,Integer AppMax,Integer AppRemaining,String DataloaderBulk,Integer DMax,Integer DRemaining,String DPartner,
    Integer DPMax,Integer DpRemaining,String FIde,Integer Fmax,Integer FRemaining,String SFMD,Integer SFMDMax,Integer SFMDRemaining,String SFTouch,Integer SFTMax,
    Integer SFTRemaining,Integer SFOMax,String SFOutlook)
    {
    System.debug('Entering in to APIUSAGE__c');
    APIUSAGE__c st = new APIUSAGE__c();
    st.ConcurrentAsync__c=ConcurrentAsyncGetReportInstances;
    st.ConcurrentSync__c=ConcurrentSyncReportRuns;
    st.Async_Max__c=Max;
    st.Max__c=Max1;
    st.SyncRemaining__c=Remaining;
    st.Async_Remaining__c=Remaining1;
    st.DailyApiRequests__c=DailApiRequest;
    st.DAPIRemaining__c=DAPIRemaining;
    st.DAPiMax__c=DAPiMax;
    st.Ant_Migration_Tool__c=Ant;
    st.Ant_Max__c=AntMax;
    st.Ant_Remaining__c=AntRemaining;
    st.App_Name__c=App;
    st.App_Max__c=AppMax;
    st.App_Remaining__c=AppRemaining;
    st.Dataloader_Bulk__c=DataloaderBulk;
    st.DMax__c=DMax;
    st.DRemaining__c=DRemaining;
    st.Dataloader_Partner__c=DPartner;
    st.DPMax__c=DPMax;
    st.DpRemaining__c=DpRemaining;
    st.ForceIDE__c=FIde;
    st.FMax__c=Fmax;
    st.FRemaining__c=FRemaining;
    st.SFMD__c=SFMD;
    st.SFMDMax__c=SFMDMax;
    st.SFMDRemaining__c=SFMDRemaining;
    st.SFTouch__c=SFTouch;
    st.SFTMax__c=SFTMax;
    st.SFTRemaining__c=SFTRemaining;
    st.SFOMax__c=SFOMax;
    st.SFOutlook__c=SFOutlook;





    insert st;
    return st.Id;
    }



    }

    ReplyDelete
  13. Hai Author, Very Good informative blog post,
    Thanks

    ReplyDelete
  14. Nice article, I loved it. Thanks for sharing and keep sharing.
    personalrekrutierung

    ReplyDelete
  15. Learn Salesforce.com developer courses online/classroom in Delhi from top training institutes and get Salesforcedeveloper certification. Get details on course fees @91-931OO96831!!

    ReplyDelete
  16. The website is looking bit flashy and it catches the visitors eyes. A design is pretty simple .
    Stellenbörse

    ReplyDelete

  17. The website is looking bit flashy and it catches the visitors eyes. A design is pretty simple .
    office 2016 professional plus 64 bit

    ReplyDelete
  18. Thanks For Your valuable posting, it was very informative
    Schulungsangebote

    ReplyDelete
  19. Your website content nice nice and interesting to observe.
    jobbörse Neunkirchen

    ReplyDelete