The REST API is a powerful web service API that allows you to interact with 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.


  • 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.

  <script src=""></script>
  <h3>REST API With Javascript</h3>
  <button id="connect">Connect to the REST API</button>
  <script type="text/javascript">
     //The clientId and consumerSecret are the ones from the Connected App
     var clientId = "xxxxxxxxxxxx";
     var consumerSecret = "xxxxxxxxxxx";
     //Authorization endpoint
     var authEndPoint = "";
     //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;

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.

      <script src=""></script>
      <h3>REST API With Javascript</h3>
      <h4>Create Account Record</h4>
      <label for="name">Account Name</label>
      <input type="text" name="Name" id="name">
      <button id="button">Submit</button>
      <div id="status"></div>
      <script type="text/javascript">
       //Get access token.
       //Because the access token is a URL parameter it needs to be decoded
          var accessToken = decodeURI(GetURLParameter('access_token'));

           //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

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

  var accountName = $('#name').val();
  if(accountName!= ''){
    //replace the below url with your domain name or
    var requestUrl = '';
    //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
      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){
       error: function(response){

            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>';
  $('<a>',{//replace this with your salesforce instance url
    text: '',
    href: '',
    target : '_blank'

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


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:


The complete code for this example can be found at

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 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 APIs, Apex, Visualforce and implementation of other developer products.

Get the latest Salesforce Developer blog posts and podcast episodes via Slack or RSS.

Add to Slack Subscribe to RSS