Calling the REST API from Visualforce Pages, Revisited

Longtime readers may remember the series of posts I wrote in early 2011 on calling the REST API from JavaScript running on Visualforce, off-platform web pages, and PhoneGap hybrid apps. Those posts spawned the 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 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:includeScript value=""/>
    jQuery(document).ready(function($) {
      // Pull 10 Accounts via the REST API
          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) {
          error: function(jqXHR, textStatus, errorThrown) {
            // Oops - what went wrong?
            alert(jqXHR.status + ': ' + errorThrown);
  <h1>Test REST API Without Proxy</h1>
  <p>10 Accounts:</p>
  <ul id="accountList">

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.

June 24, 2013

Leave your comments...

Calling the REST API from Visualforce Pages, Revisited