Calling the Force.com REST API from Visualforce Pages, Revisited

Longtime readers may remember the series of posts I wrote in early 2011 on calling the Force.com REST API from JavaScript running on Visualforce, off-platform web pages, and PhoneGap hybrid apps. Those posts spawned the Force.com JavaScript REST Toolkit (in particular, forcetk.js), which, in turn, became part of the Salesforce Mobile SDK.

While JavaScript Remoting (see also the blog post on RemoteTK) is a more efficient mechanism for accessing data in Force.com from JavaScript, since it doesn’t consume API calls, it’s still sometimes useful to be able to call the APIs from JavaScript. One of the tasks that forcetk.js performs is to route API calls via the Ajax Proxy, since the REST API is not exposed on Visualforce servers, and JavaScript’s Same Origin Policy prevents us from calling it directly.

Correction – the REST API wasn’t exposed on Visualforce servers. From Summer ’13, it is!

Now you can access REST API URLs directly from JavaScript on Visualforce. Here’s a minimal example:

<apex:page>
  <apex:includeScript value="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js"/>
  <script>
    jQuery(document).ready(function($) {
      // Pull 10 Accounts via the REST API
      $.ajax('/services/data/v28.0/query?q=SELECT+Name+FROM+Account+LIMIT+10',
        {
          beforeSend: function(xhr) {
            // Set the OAuth header from the session ID
            xhr.setRequestHeader('Authorization', 'Bearer {!$Api.Session_ID}');
          },
          success: function(response) {
            // We got 'em - append our records to the HTML list
            $.each(response.records, function(index, record) {
              $('#accountList').append('<li>'+record.Name+'</li>');
            });
          },
          error: function(jqXHR, textStatus, errorThrown) {
            // Oops - what went wrong?
            alert(jqXHR.status + ': ' + errorThrown);
          }
        }
      );
    });
  </script>
  <h1>Test REST API Without Proxy</h1>
  <p>10 Accounts:</p>
  <ul id="accountList">
  </ul>
</apex:page>

With the result:

I need to do some more rigorous testing before I remove the call to the Ajax Proxy from forcetk.js, but I wanted to share this nugget today, since it’s immediately useful in answering this question on Salesforce StackExchange. In the meantime, if you want to give this a quick try with a Visualforce page that is using ForceTK, insert the following code after the call to client.setSessionToken('{!$Api.Session_ID}');

    client.proxyUrl = null;
    client.instanceUrl = '';

This should work – let me know in the comments if you encounter any problems!

UPDATEhere’s a Visualforce page that lets you execute arbitrary REST queries.

Published
June 24, 2013
Topics:

Leave your comments...

Calling the Force.com REST API from Visualforce Pages, Revisited