Accessing Salesforce Data from Backbone.js Using the REST API

Author: Surbhi Chaturvedi

Salesforce Platform is the next generation of CRM service provider, it is a pioneer in terms of providing CRM software as a service. is a development environment that allows you to build cloud apps, as well as extend Salesforce CRM apps. You access through a web interface. It provides REST API’s to the developers to search, query, create, and modify standard or custom objects. Mobile and Web Developers are generally accustomed to the REST API’s accessing any data or service provided by a backend server.

Backbone.js is a web framework to organize your web app in an MVC (Model – View – Controller) structure. Backbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface. The advantage of using Backbone.js over other similar frameworks is that it is a very lean framework and doesn’t force a particular architecture on the user for their web app.

In this tutorial, I will walk you through building a web app using Backbone.js, which provides an interface to access the accounts and contacts related details. Then, we will look at how to integrate this app with API’s to access data in a application.

Here are the things we will do in this tutorial:

1. Setting up a Developer Edition account to get started.

2. Writing a simple code in Backbone.js to access Contact records from Salesforce.

3. Deploying the application on Heroku

Setting up a Salesforce Developer Edition Account

1. Go to, and sign up for your Developer Edition (DE) account. For the purposes of this example, I recommend sign up for a Developer Edition even if you already have an account. This ensures you get a clean environment with the latest features enabled.

2. Navigate to to log into your developer account.  

2.  Go to Build ->Create -> Apps  

3.  Click on the “New” button on the Connected Apps list (You will need to scroll down to the end of the page.)

Connected apps in are a way to share your Salesforce data with an external app using OAuth 2.0 authentication.

  1. Navigate to the “New Connected Apps” Page. You will be required to fill the following fields:
  • Connected App Name –  your custom app name here
  • API Name – this will be the same as the connected app name (it will be auto populated )
  • Contact Email, Contact Phone – your email address and phone number
  • Logo Image URL, Icon URL – choose from the sample as we have done or upload your own custom logo.

Select “Enable OAuth Settings”; this will allow you to add the callback URL for the app you have created (For me it’s – Then, select the OAuth Scopes and save this page:

You will then be taken to a page which will give you the consumer key; keep this safe, as you will need it later

Backbone.js Application

Here is a simple code to set up the model and collection to read Contact Records from Salesforce. Integrating Backbone.js’s REST API can be easily done usingBackbone.Force, a plugin that handily adapts Backbone.js’s Model and Collection to our purposes, building on theForceTK library to access the REST API. After initializing a ForceTK client and passing it to Backbone.js.Force, use the code below:

// Models
app.Contact = Backbone.Force.Model.extend({
    type: 'Contact',
    fields: ['Id', 'Name', 'Email', 'FirstName', 'LastName']
// fields - are the list of fields you want to add to your model
app.ContactsCollection = Backbone.Force.Collection.extend({
    model: app.Contact,
    query: "WHERE IsDeleted = false" // filter

We then create an html template to render each contact:

<script type="text/template" id="contact-template">
    <% if (typeof(Id) !== 'undefined') { %>
        <%- Name %>
    <% } else { %>
        <%- Name %>
    <% } %>

Use render() function for the ContactView:

// renders individual Contact list item (li)
app.ContactView = Backbone.View.extend({
    tagName: 'li',
    template: _.template($('#contact-template').html()),
    render: function(){
        return this; // enable chained calls

The view just puts the Model’s data into the DOM via template. We can extend this code by simply adding more fields to the Model and to the template without having to worry about how to update the DOM and where we query the REST API. The remainder of the sample builds on the above foundation in a very systematic way. There is a Contact List view (Contact List view refers to the view mode that has the number of contacts listed) that knows how to render itself (via a template) as a sequence of ContactView objects. There is also a Contact Detail view (this view shows the single contact details) that, again, uses a template to render some of the Contact records fields and allows saving, editing and deleting the Contact records. Finally there is a Router that handles the navigation between the various views, which in our app switches between Contact List and Contact Detail views. The ContactDetailView save() function is using the Model to update the record, and navigating back to the Contact list view via the Router:

app.ContactDetailView = Backbone.View.extend({
    save: function(){, {
            success: function(model) {
                // Setting trigger to true reloads the contact list - we want
                // the latest data from Salesforce!
                app.router.navigate('contacts', {trigger: true});
            error: function () {
                alert('Error saving');
        return false;

Let’s now take a look at how the Router plugs a collection and view together with the DOM so that when you request the web page, you see a contact list:

//Define the Application Router
app.Router = Backbone.Router.extend({
    routes: {
        "": "contacts",        // Empty or missing hash fragment
        "contacts":"contacts", // #contacts
        "new": "newContact",   // #new
        ":id": "contact"       // #[record id]
    contacts: function() {
        var contactsCollection = new app.ContactsCollection();
        $.mobile.loading( "show", {
            text: 'Loading Contacts',
            textVisible: true
        contactsCollection.fetch({success: function(){
            $.mobile.loading( "hide" );
            $("#contacts-content").html(new app.ContactsView({
                model: contactsCollection
            // Let jQuery Mobile do its stuff
            $("#contacts-content").trigger( 'create' );
            $.mobile.changePage( "#contacts" , {
                reverse: false,
                changeHash: false
    // Route handlers for creating and modifying Contact records.

You can also try modify and other functions using the source code in the GitHub repository.

Publishing the App on Heroku:

Now, to see this app working, you must deploy the application on Heroku. You will need to have a Heroku account to deploy the app, and to install Heroku Toolbelt. You can create the free account and download the toolbelt here.

  • Once the Heroku Toolbelt is installed, clone the sample code from github.
  • Move to where you have cloned the code from github and log into Heroku with your credentials.
  • Create a new app on Heroku


cd folder where you cloned the code
	heroku login
		Enter your Heroku credentials.
Password (characters will be hidden):
Authentication successful.

          heroku apps:create
Creating sheltered-earth-8649... done, stack is cedar |
Git remote heroku added

You must make sure that the Heroku app name is the same as the one you have mentioned in the call back URL in your Salesforce DE. You can always go back to Salesforce platform and edit the call back URL for your connected app if you need to do so. The callback URL in our case will be: https:// Once we have created the Heroku app, we will need to expose the Consumer Key, which we saved when we created the connected app in Salesforce and our application URL on Heroku (in our case it’s https://, to the Heroku environment. That way, our app can access the Salesforce data associated with the account.

	heroku config:add app_url=[APP URL]
	heroku config:add client_id=[CONSUMER KEY]

Deploy the app on Heroku by pushing our code through git:

	git push heroku master

The Salesforce app should now be live on your Heroku app url. You can open it from your terminal too.

	heroku open	

The Salesforce app will authenticate the user using an OAuth token and provide access to the contacts in the associated Salesforce account.


To summarize, in this tutorial we started by creating a new app in the Salesforce platform, writing a Backbone.js code to add the Contacts and then deployed this application using Heroku, thus showing the user how to connect to the Salesfore Platform using OAuth in order to retrieve customer data.


For a comprehensive set or resources, check out:


This is a sponsored blog post; not a recommendation. All sponsored blog posts, some of which we may receive compensation to perform, express the views of the advertiser only. Any product claim, statistic, or other representation should be verified with the provider.