Creating a jQuery application using the Force.com REST API

The REST API is a powerful web service API that allows you to interact with Force.com. Its advantages include ease of integration and development, and it’s an excellent choice of technology for use with mobile applications and Web 2.0 projects.

This article will guide you through the process of creating a simple jQuery application that connects to the REST API and allows you to create records in your salesforce organization directly from an external website. The same process could be used to create a mobile application for your sales reps, or integrating a backend system with salesforce to sync data.

Requirements

  • A salesforce developer edition
  • A web server that runs on HTTPS and that is accessible to the Internet. This is necessary to host the HTML files.

Step 1. Creating a Connected App

Because we are creating a new application that will connect to salesforce, a Connected App is needed to  make salesforce aware of this application.

  1. Go to Setup | Create | Apps and click New under Connected Apps.
  2. Specify the Name and API Name.
  3. Select Enable OAuth Settings.
  4. Under Callback URL specify the URL of the web page that we’ll use to create account records.
  5. Move all the available OAuth scopes to the Selected box under Selected OAuth Scopes.
  6. Click Save.

You should now have a Consumer Key and Consumer Secret, keep these values handy.

Step 2. Choosing the correct Authentication flow

The first step in connecting to the REST API is to authenticate the user and get a valid access token (session Id) that can be used in subsequent calls to the API.

Depending on the type of application you are creating, the authentication flow will be different. In this case, we’ll use the User-Agent OAuth Flow because our application runs in the client side (the user’s browser).

At a basic level, the flow is as follows:

  1. The application redirects the user to the authorization endpoint passing the required parameters, i.e response_type, client_id and redirect_uri.
  2. The user logs in with their salesforce credentials.
  3. The authorization endpoint redirects the user to the redirect URL (this is the web page you specified in the Connected App) and appends the access token (session Id) to the URL.
  4. You can then use this access token to make calls to the API.

Step 3. Create the initial html page

Create an HTML page called ConnectRESTAPI.html.  This page has a button that allows the user to connect to the REST API. Note this is not the same page that we configured as the callback URL, we will work on that one on the next step.

<html>
 <head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
 </head>
 <body>
  <h3>REST API With Javascript</h3>
  <button id="connect">Connect to the REST API</button>
  <script type="text/javascript">
    $(document).ready(function(){
     $('#connect').click(function(){
     //The clientId and consumerSecret are the ones from the Connected App
     var clientId = "xxxxxxxxxxxx";
     var consumerSecret = "xxxxxxxxxxx";
     //Authorization endpoint
     var authEndPoint = "https://login.salesforce.com/services/oauth2/authorize";
     //response_type must be set to token
     var responseType = "token";
     //This is the callback URL from the connected app
     var redirectURI = "Your redirect URL page";
     //Construct the URL with the required parameters
     var requestURL = authEndPoint+'?client_id='+clientId+'&response_type='+responseType+'&redirect_uri='+redirectURI;
     //redirect the user to the endpoint 
     window.location = requestURL;
     });
  })
 </script>
 </body>
</html>

Step 4. Create the page used as the callback URL

Create an HTML page called UseRESTAPI.HTML. This is the page that we configured as the callback URL and will also be the main page from where we will make API calls.

<html>
  <body>
    <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    </head>
      <h3>REST API With Javascript</h3>
      <h4>Create Account Record</h4>
      <label for="name">Account Name</label>
      <input type="text" name="Name" id="name">
      <br><br>
      <button id="button">Submit</button>
      <div id="status"></div>
      <script type="text/javascript">
        $(document).ready(function(){
       //Get access token.
       //Because the access token is a URL parameter it needs to be decoded
          var accessToken = decodeURI(GetURLParameter('access_token'));
          console.log(accessToken);

           //Use this function to get the access token from the URL
           function GetURLParameter(sParam)
            {
              var mainURL = document.location+'';
              var pageUrls = mainURL.split('#');
              var sURLVariables = pageUrls[1].split('&');
              for (var i = 0; i < sURLVariables.length; i++) 
                {
                  var sParameterName = sURLVariables[i].split('=');
                  if (sParameterName[0] == sParam) 
                    {
                      return sParameterName[1];
                      }
                  }
               }

When the authorization endpoint redirects the user to the redirect URL, the access token is appended as follows https://mycallbackurl.com#access_token.

The GetURLParameter function allows you to retrieve this value. Pay special attention to the decodeURI() method. If you don’t decode the access token, the server might not understand some of its characters and the API call will fail to authenticate.

In order to create an Account record via the REST API, we need to submit a HTTP POST request to /services/data/v20.0/sobjects/Account/.

Remember that when making calls to the REST API, you need to use the access token that was granted to you. This is done by adding an Authorization header with the value of “Bearer +access token” as seen in the $.ajax request.

//Create Account Record button click
$('#button').click(function(){

  var accountName = $('#name').val();
  if(accountName!= ''){
    //replace the below url with your domain name or yourInstance.salesforce.com
    var requestUrl = 'https://eu5.salesforce.com/services/data/v20.0/sobjects/Account/';
    //create a javascript object with the account field values
    var accountInfo = {
        "Name" :accountName
                        }
    //convert the object to a JSON string
    var accountInfoJson = JSON.stringify(accountInfo);
    //send POST with ajax
    $.ajax({
      type: 'POST',
      url : requestUrl,
      //add the authorization header including the access_token
      headers : {
        'Authorization' : 'Bearer '+accessToken,
         'Content-Type' : 'application/json'
                  },
       data : accountInfoJson,
       success : function(response){
                    displayAccountInfo(response);
                            },
       error: function(response){
                    displayError(response);
                            }
                        });

         }else{
            alert('Please specify name');
             }

            })

Finally, we create two functions that will be used to process the response from salesforce, one is used if the account is successfully created and the other one is used if an error occurs.

//If account is successfully created
function displayAccountInfo(responseObject){
  var statusMessage = '<p>Success! Your account has been created, click on the link below.</p>';
  $('#status').append(statusMessage);
  $('<a>',{//replace this with your salesforce instance url
    text: 'https://eu5.salesforce.com/'+responseObject.id,
    href: 'https://eu5.salesforce.com/'+responseObject.id,
    target : '_blank'
   }).appendTo($('#status'));
       }

//If an error message occurred
function displayError(responseObject){
  var responseJson = responseObject.responseJSON;
  var statusMessage = '<p>A problem has occurred, please contact your administrator</p>';
  $('#status').append(statusMessage);
   $('<p>',{
       text : responseJson[0].errorCode+": "+responseJson[0].message
    }).appendTo($('#status'));

      }
       })
    </script>
   </body>
</html>

Step 5. Whitelist your domain

Because your page is on a different domain that your salesforce organization, we need to whitelist it to allow javascript callouts to access resources from your organization.

  1.  Go to Setup | Security Controls | CORS.
  2. Add your domain to the list of Whitelisted Origins.

Test your application

  1. Load the initial HTML page and click the “Connect to the REST API” button.
  2. You will be asked to log into your org and to grant permission to the application.
  3. You will then be redirected to the main HTML page.
  4. Add a name to the “Name” field and click submit, if everything works fine you should see something like this:

SuccesScreen.png

The complete code for this example can be found at https://github.com/pgonzaleznetwork/SFDC-Projects

What next?

You should now have the basic knowledge to start creating applications with the REST API. This example focused on creating applications on the client side, but you can also create applications on a server using a server side code like Java or PHP. Check out the Force.com REST API Developer’s Guide to learn more.

About the Author

Pablo Gonzalez is a member of the Mission Critical Support team which provides the highest level of support to enterprise Salesforce customers. They also assist developers to troubleshoot their integration with salesforce.com APIs, Apex, Visualforce and implementation of other salesforce.com developer products.

Leave your comments...

Creating a jQuery application using the Force.com REST API