Tl_web_api_icon 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:

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

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

Add to Slack Subscribe to RSS