Calling the REST API from JavaScript in Visualforce Pages

This is part one of a three part series showing how to call the Force.com REST API from JavaScript in various scenarios. Part two, Calling the REST API from JavaScript… from Anywhere!, explains how to call the REST API from JavaScript served from a domain outside Force.com, while part three, Calling the REST API from JavaScript in PhoneGap, looks at JavaScript running in mobile apps on the PhoneGap framework.

One of the great things about working in the Force.com developer evangelism team is the cross-pollination of ideas. Prompted by some questions in the Developer Boards, a couple of us have been trying different approaches to allow JavaScript code to call the Force.com REST API, working around the restrictions imposed by the same origin policy. I did some work using a simple PHP proxy, hosted, with my JavaScript, on a separate site, while Sandeep tried out YQL, but neither solution was particularly satisfying – my proxied approach required a separate host, while Sandeep’s had all the data flowing through Yahoo.

It was a chance remark by Sandeep that prompted me to look to the AJAX Toolkit, a wrapper for the SOAP API, for inspiration. The AJAX Toolkit provides a JavaScript library and SOAP endpoint on the same host as your Visualforce page; unfortunately, the corresponding REST endpoint does a redirect to the canonical URL, which doesn’t work for my purposes, since it breaks same origin policy, but, looking at the AJAX Toolkit, I noticed the AJAX Proxy, a component designed to allow your JavaScript to call out to API endpoints outside the Force.com platform.

With some lateral thinking and Josh‘s recent Cookbook recipe Using jQuery in a Visualforce Page as a guide, I was able to quickly repurpose my proxy-based approach to use the AJAX Proxy to call the REST endpoint, and, in a couple of hours, had a JavaScript app running with describe, query, create, retrieve, update and delete all operational, allowing you to write code like this:

// Get a reference to jQuery that doesn't conflict with Visualforce
$j = jQuery.noConflict();
// Get an instance of the REST API client
var client = new forcetk.Client('{!$Api.Session_ID}');
// Get an account name and put it somewhere on the page
client.query("SELECT Name FROM Account LIMIT 1",function(response){
    $j('#accountname').html(response.records[0].Name);
});

You can find the embryonic project at GitHub – it’s currently in my own profile – we’ll move it over to the DeveloperForce profile as it matures. If you’ve been waiting for a way to call the Force.com REST API from JavaScript, go take a look and see if it meets your needs.

UPDATE – here’s a brief video showing the toolkit in action.

//www.youtube.com/watch?v=qNA8nxfPgBU

Leave your comments...

Calling the REST API from JavaScript in Visualforce Pages