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. 




38 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. Thank you. Web design Hyderabad is a competitive market and Attrait Solutions offer excellent service at the right price.Web design encompasses many different skills and disciplines in the production and maintenance of websites.

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

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

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

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

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

    ReplyDelete
  13. Its the best information for me..Am got the lots of information in your post..Thank you for sharing the useful information
    Website Designing Company In Delhi | Website Development Company In Delhi

    ReplyDelete
  14. I am a regular user of your post, this one also was very interesting and well written. keep sharing the great work Web Design Company Bangalore | Website Design Company Bangalore

    ReplyDelete
  15. useful information for me..getting the lots of information in your post..Thank you for sharing the useful information

    Website Designing Company in Delhi | Website Designing Company in Rohini | Website Designing Company in Kirti Nagar

    ReplyDelete
  16. Wow...!! Same this is one amazing article for people who didn't know that they can reach more people through their website. I would love to add something like this article in my blog and talk also about Web Design And Development in Hyderabad. Thank you. This is such an eye opener for so many.
    I would like to share this blog with you: web development company in Hyderabad
    Please Let me know what you think...!

    ReplyDelete
  17. 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
  18. Thank you for sharing such an informative news with us. Keep on sharing Contents like this. You can also share this content on various sites like the Automation Associates LLC site.

    ReplyDelete
  19. I have analyzed your post. Excellent details you did here. I enjoyed reading your blog, and it is both instructional and enjoyable. Share this most interesting post in other sites like OS Business Opportunities, the innovative Asaim Japan site and also to the Jfissures site followed by Free Smaple 411 and lastly to the sites like Johny Adams sites.

    ReplyDelete
  20. The post is very informative. It is a pleasure reading it. I have also bookmarked you for checking out new posts. You can also share this valuable content on other platforms such as Blogspot, the famous Wordpress site, the innovative Tumblr site and also the sites like Medium and the famous Live Journal site.

    ReplyDelete
  21. Thank you for sharing this information. Come back again for more interesting stuff like this post. You can share this informative post in Social Media sites like the worldwide famous Facebook, the all-time favorite Twitter and the most interesting Google Plus site, business site LinkedIn and also to the Infographic site Pinterest to generate more traffic to your blog post.

    ReplyDelete
  22. This blog is the general information for the feature. You got a good work for these blog.We have a developing our creative content of this mind.Thank you for this blog. This for very interesting and useful.
    Sales Fore CRM Training in Chennai

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

    ReplyDelete
  24. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...
    Android Training in Chennai
    Ios Training in Chennai

    ReplyDelete
  25. Thank you for sharing this excellent post. The post is handy and useful. You can also share these type of posts in the platforms like Wordpress, the famous Blogspot site, the all favorite Tumblr site and also in the location like Medium and lastly to the Live Journal site.

    ReplyDelete
  26. This is the kind of post I was searching for today. Awesome post and very useful and easy to read. Thank you for sharing this wonderful; post. You can also share these post on the Social media's like Google Plus, the all time hit Facebook, the notorious Twitter, the business sharing site LinkedIn and lastly to the famous Infographic site Pinterest to gain more traffic to your blog post.

    ReplyDelete
  27. Nice informative post. Thank you so much for sharing this post. For more information please gothrough our link:
    SMO Services Mumbai

    ReplyDelete
  28. This Article is Very HelpFul For me You Can Also Visit my Website http://www.hostone.pk/ HostOne is a Pakistan based web hosting company, We Offered You 30% Off Web Hosting in Pakistan providing both providing reliable hosting services since 2011
    Best Web Hosting in Pakistan

    ReplyDelete

  29. Thanks for sharing this knowledgefull information.

    Business this day has become more competitive in nature to the extent that all business owners need to do something fast in order to remain in business. Proper collaboration is what most business needs to make progress in this competitive world. The experts here have what it takes to render highest quality and dedicated as well as targeted web development services which can give your customers what they need at any point in time. Through the result-oriented team working here you will be sure of getting premier website application development services that will meet the needs of your audience.

    Website application development
    Software Development Services
    Android App development Services

    ReplyDelete
  30. Great article, I am so impressed, I am so happy to read this very awesome blog, I get a lot information to read this very awesome post, Thank you so much for sharing this post. Keep it up.
    Socks manufacturer in pakistan
    digital marketing agency in pakistan

    ReplyDelete
  31. Good work…unique site and interesting too… keep it up…looking forward for more updates.and blog keep it up I really enjoy the blog post…
    SEO Company Lucknow , Software Development in Lucknow

    ReplyDelete
  32. Web Design Sydney: It is a great sharing...I am very much pleased with the contents you have mentioned. I wanted to thank you for this great article.Logo Design Sydney

    ReplyDelete
  33. Lovely blog with much more interesting article, I will keep on reading your update. Thanks for the share Ear Plugs for Swimming Ear plugs for Sleeping Custom Ear Plugs

    ReplyDelete