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. 




94 comments:

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

    PHP web development company in Mumbai

    ReplyDelete
  2. 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
  3. I was looking for Web Design Nagpur Jobs came across this blog . Good information provided.Thanks for sharing with us.

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

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

    ReplyDelete
  6. 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
  7. Thank you for sharing the useful information...I have a getting the lots of information...
    Website Development in Bangalore | Website Designing Bangalore

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

    ReplyDelete
  9. 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
  10. Hai Author, Very Good informative blog post,
    Thanks

    ReplyDelete
  11. 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

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

    ReplyDelete
  13. Awesome,
    Thank you so much for sharing such an awesome blog...
    Salesforce development Company

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

    ReplyDelete
  15. i like your post.... as your post provide useful information to me...thanks for sharing... keep updating..

    http://www.arosolchemicals.com/products.htm

    organic feed additives | veterinary feed additives | Pig and swine feed additives | Veterinary Product Manufacturer in India,Delhi | poultry feed supplements

    ReplyDelete
  16. Hi,
    Thanks for sharing a very interesting article about Salesforce REST Webservices - Part I. This is very useful information for online blog review readers. Keep it up such a nice posting like this.

    From,
    Maestro Infotech,
    Web Design Company Bangalore

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

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

    ReplyDelete
  19. A designer knows he has achieved perfection not when there is nothing left to add, but when there is nothing left to take away.Web Design Services

    ReplyDelete
  20. Thank a ton for sharing this valuable information with us. I loved your article. salesforce consultant.

    ReplyDelete
  21. great and nice blog, thanks for sharing such a nice post with us, keep sharing!!
    DevOps Online Training

    ReplyDelete
  22. Hi,

    Thanks for sharing a very interesting article about Salesforce REST Webservices - Part I. This is very useful information for online blog review readers. Keep it up such a nice posting like this.

    Regards,
    WondersMind,
    Web Design Company Bangalore

    ReplyDelete
  23. Assuredly beneficial bit of information published by you. Certainly this might be advantageous for numerous seekers. Keep on sharing this worthwhile articles. Professional Web design services are provided by W3BMINDS- Website designer in Lucknow.
    Web development Company | Web design company

    ReplyDelete
  24. This is an best post. It is Really very informative concept.I like it and help me to development very well.Thanks alot for this brief explanation and very nice information.sales force online training

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

    ReplyDelete

  26. Really it is very useful for us..... the information that you have shared is really useful for everyone. If someone wants to know about Taxi Service App and Health Management Software I think this is the right place for you.
    Car Rental Application | Taxi Software | Health and Safety software

    ReplyDelete
  27. Thanks this is really important information for us casino poker guru

    ReplyDelete
  28. Good valuable information... I have learned a lot from this blog.
    Android game development company

    ReplyDelete
  29. Very nice… i really enjoy to read your blog. Very useful information on it. Please keep posting and sharing.

    Digital Marketing Agency in Jaipur

    ReplyDelete
  30. AWS
    Mind Q Systems provides AWS training in Hyderabad & Bangalore.AWS training designed for students and professionals. Mind Q Provides 100% placement assistance with AWS training.

    Mind Q Systems is a Software Training Institute in Hyderabad and Bangalore offering courses on Testing tools, selenium, java, oracle, Manual Testing, Angular, Python, SAP, Devops etc.to Job Seekers, Professionals, Business Owners, and Students. We have highly qualified trainers with years of real-time experience.




    ReplyDelete
  31. Very interesting post really check crypto market here

    ReplyDelete
  32. I am really happy to say it’s an interesting post to read. I learn new information from your article; you are doing a great job. Keep it up…


    iClass Gyansetu in Gurgaon

    ReplyDelete


  33. Techforce services is a Salesforce Consulting Services in Australia Specialising in delivering end to end Salesforce solutions ,Consulting, Implementation DevOps partners in australia We deliver applications and services more rapidly and reliably, but it’s more than a methodology – it cuts to the very core.Salesforce Data Analytics let us help you become a data driven organisation and ensure your data is working hard for your business This includes implementi
    Salesforce consulting companies
    Salesforce Services
    Staff augmentation companies
    Salesforce integration companies
    Salesforce Implementation services
    Salesforce DevOps partners
    Salesforce DevOps
    Managed project services

    ReplyDelete
  34. Text messages have become the most effective and reliable tool for marketers to send vital information right in front of the eyes of audiences. In addition to this, WhatsApp has equipped businesses to tap into the world of rich media communication and connect with audiences over the most popular messaging channel. Thus, business ventures who haven’t touched WhatsApp yet are heading to Salesforce WhatsApp integration in addition to SMS integration for Salesforce to reap WhatsApp benefits along with texts.

    ReplyDelete
  35. This blog contains too much information. Thank you for posting this and please keep sharing your good thoughts.
    Upcoming projects in Sector 79 Noida

    ReplyDelete
  36. We are known as the best iPhone Insurance provider in India. You may connect with us to get the fast insurance services.

    ReplyDelete
  37. This is really good blog information thanks for sharing. very informative.
    Website designing company in Noida

    ReplyDelete
  38. Thanks For Sharing Such A Great Article, Please Read Our Article And Keep Them Up.
    Brackish Water Desalination 150000 GPD R.O. System Djibouti

    ReplyDelete
  39. Wow, cool post. I'd like to write like this too - taking time and real hard work to make a great article... but I put things off too much and never seem to get started. Thanks though
    Website design company Warsaw

    ReplyDelete
  40. Are you interested to grow your online business worldwide? If yes then you must join the best SEO Company in Ghaziabad that provides high-class SEO service.

    ReplyDelete
  41. I recommend that css founder is the best company for website design and development. It is known as the best website designing company. Website design company Lublin

    ReplyDelete
  42. Wow, cool post. I'd like to write like this too - taking time and real hard work to make a great article... but I put things off too much and never seem to get started. Thanks though Digital Marketing Company in bhandup

    ReplyDelete

  43. 1 BHK, 2 BHK Residential Property in Haridwar for Sale near Har ki Paurion Main Rishikesh Highway amidst the
    scenic beauty of residential projects in Haridwar near Ganga . Ready to move flats for sale in Haridwar are
    available with a bank loan facility

    ReplyDelete
  44. Need professional WordPress Web Design Services? We're experts in developing attractive mobile-friendly WordPress websites for businesses. Contact us today! https://just99marketing.com/wordpress-web-design

    ReplyDelete
  45. This is nice and more informative, Thank you for sharing it!

    Java Training in Hyderabad

    ReplyDelete
  46. Your skills and efforts are truly appreciated. Keep up the great work! I wanted to take a moment to let you know that you can also good job with affordable website design work

    ReplyDelete
  47. Thank you for sharing valuable insights on Salesforce REST Webservices! Your expertise shines through, offering clarity in a complex subject. As a Dubai-based website development and design agency, we're constantly seeking to enhance our understanding.

    ReplyDelete