Back in Spring 2011 (the season, not the release!), I wrote the Force.com JavaScript REST Toolkit (or ForceTK for short, after forcetk.js, its core JavaScript library), wrapping the Force.com REST API for easy access from JavaScript running on Visualforce pages, external servers, and hybrid mobile apps. Since then, the toolkit has seen wide adoption, most notably as part of the Salesforce Mobile SDK, but it has always bugged me that JavaScript on Visualforce pages would consume API calls (a limited resource), limiting the usefulness of the toolkit somewhat.

Coincidentally, in Spring ’11 (the release this time), JavaScript Remoting, a mechanism for calling Apex controller methods (annotated with @RemoteAction) from JavaScript, debuted as a developer preview. I’ve used Remoting a few times, writing @RemoteAction methods for each specific situation, but it wasn’t until I read Don Robins’ second article on Developing Mobile Applications with Force.com and Sencha Touch, with its mention of the Sencha proxy for binding JavaScript controller logic to @RemoteAction methods in an Apex controller, that I realised that I could write a set of @RemoteAction methods for general purpose data access and a corresponding set of JavaScript wrappers exposing the same interface as ForceTK, all conveniently wrapped in a Custom Component - RemoteTK.

Quoting from the updated toolkit README:

The RemoteTK Visualforce Custom Component (comprising RemoteTK.component and RemoteTKController.cls) provides an abstraction very similar to the REST API, implemented via @RemoteAction methods in the component’s controller. The advantage of this mechanism is that no API calls are consumed. A disadvantage is that upsert is not currently implemented. [UPDATE - Spring '13 added the ability to pass sobject type variables to Database.upsert]

[...]

Add RemoteTKController.cls and RemoteTK.component to your org by creating an Apex Class and a Component and pasting in the respective content, pasting the files into a Force.com IDE project, or by using the Force.com Migration Tool.

Your Visualforce page will need to include the component and create a client object. An absolutely minimal sample is:

<apex:page>
    <!-- Include the RemoteTK component -->
    <c:RemoteTK />
    <apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js" />
    <script type="text/javascript">
        // Get a reference to jQuery that we can work with
        $j = jQuery.noConflict();

        // Get an instance of the RemoteTK client
        var client = new remotetk.Client();
        client.query("SELECT Name FROM Account LIMIT 1", function(response){
            $j('#accountname').html(response.records[0].Name);
        });
    </script>
    <p>The first account I see is <span id="accountname"></span>.</p>
</apex:page>

More fully featured samples are provided in RemoteTKExample.page and RemoteTKMobile.page.

Since I started work on RemoteTK just last Friday it’s probably best described as ‘embryonic’, but I ported the two ForceTK sample apps to RemoteTK with just three changes (include the RemoteTK component, get an instance of the RemoteTK client, rather than ForceTK, and delete the call to setSessionToken()) and they seem to work well.

A few known issues at present:

  • Upsert is not supported – I haven’t figured out how to do this with a dynamic external field ID name. It might not be possible.
  • describe() is a very minimal implementation – just enough to get the sample apps working.
  • 0% test coverage – this prevents me from creating an unmanaged package. Much more soluble than the upsert issue!
So, if you’ve been using forcetk.js from Visualforce, give RemoteTK a try (it’s part of the expanded Force.com JavaScript REST Toolkit), send me a pull request if you fix any of the above, and/or file issues on the GitHub project.
tagged , , , , Bookmark the permalink. Trackbacks are closed, but you can post a comment.
  • Don Robins

    Really cool Pat! Just starting to play with it…

  • Peter Goriev

    Thanks Pat! Costy API calls are really an issue for us.. Would be great if you manage to solve the upsert problem as well.
    Cheers,
    Peter

  • Anonymous

    Hi Pat,I’m planning to invoke an external rest API from vf page . Can I use this toolkit in this case ??

    • http://blog.superpat.com/ Pat Patterson

      Hi Rakesh – no – the Force.com JavaScript REST Toolkit is a lightweight JavaScript library wrapping the Force.com REST API. You will need to use XMLHTTPRequest or jQuery ajax() to call an external REST API from JavaScript in a VF page, or the Apex HTTP client to call it from the page controller.

  • http://twitter.com/FloFlorFlorcita florencia

    prueba

  • Jeff Trull

    Hi Pat, thanks for putting this together. I’d like to switch my existing code over (it seems cleaner to use a single Salesforce-supported codebase) but I wanted to ask about a couple of design decisions:

    1. It seems like the RemoteTk class interface is String based with manual (JSON method) serialization/deserialization. Did you want to avoid the built-in Remoting serialization (i.e., for object parameters and return values)?

    2. It looks like the CRUD operations are not batched, i.e., it’s a single SObject each time. In my primary application (grids), it’s common to accumulate changes and then write all the dirty records at once – for example, when the user presses a Save button. I worry this might impact performance. Any chance for some batch methods?

    Anyway thanks again for this, I’m sure you’re saving work for a lot of developers!

    • http://blog.superpat.com/ Pat Patterson

      Hi Jeff, apologies for not replying in a more timely manner!

      0. Just to make clear, RemoteTK is NOT Salesforce-supported. Code in https://github.com/developerforce/ is unsupported, as-is. If it helps, then great, but you can’t file a ticket on it.

      1. No conscious avoidance – I just did the minimum to emulate ForceTK’s JavaScript interface. It’s very possible that it could be done in a better way. Feel free to hack it to suit and send me a pull request!

      2. That would be cool – see the advice above on hacking and sending a pull request :-)

      Or, file issue(s) and I’ll get to them as I can. Sample code showing how you’d like it to work would be cool :-)

  • brad parks

    By “The advantage of this mechanism is that no API calls are consumed”, do you mean that the “Total number of executed code statements” value of 200,000 doesn’t get affected by RemoteTK calls? I got this info from the following Salesforce page on API limits:

    http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_gov_limits.htm

    • http://blog.superpat.com/ Pat Patterson

      When a RemoteTK call takes place, Apex code does run, to the order of a few dozen statements. The total number of executed code statements limit applies to each call (not per day), so there should be no issue.

      • brad parks

        So what does “The advantage of this mechanism is that no API calls are consumed” mean then? I get that a dozen or so would be done by RemoteTK, but is there some “vast” savings hidden here somewhere that I’m not getting? ie is it really worth using RemoteTK over the straight REST approach, since the REST api gives more features?

        As you can probably tell, I’m new to this whole scene, and am trying to make some good decisions up front. My choices seem to be:

        - all code in Apex, and UI code done in VisualForce
        - all code in Apex, called by RemoteTK, UI in Javascript
        - all code in Apex, called by REST, UI in javascript

        • http://blog.superpat.com/ Pat Patterson

          Ah – API calls are different from script statements. The API call limit is per user, per day, so if a large population of users are hitting the REST API intensively from a mobile app, this could become a limiting factor.

          As well as the choices you list, you can do more or less of your business logic in Apex or JavaScript. The ‘out of the box’ Force.com REST API (and RemoteTK) gives you complete access to your data, so you can code the entire app in JavaScript. Even then, if there are operations that comprise multiple API calls, it makes sense to implement them as custom Apex REST methods and make a single API call from your app.

          Hope this helps!

          • brad parks

            Cool ! Thanks Pat…. I get it now….

  • Carolina Ruiz Medina

    Hi Pat! Thanks for your post!!
    We’ve used this approach in my development :) . I would like to ask you about JSRemoting and API limits. I know that have been 2 years from this post but having some conversations seems like the JSRemoting call is counting agains API calls Limit in the organization. Personally, I tested in several orgs (yesterday again ) and I found that JSRemoting calls don’t count against API limit ( this was my thought before ) … however as I said, after some conversations and some posts, I’m starting to doubt. I created a case with SF but I didn’t get anything back yet :( , therefore I’m wondering if you could please let me know if JavaScript Remoting Calls count against API limit ?? . Thank you very much in advance !!

    • Carolina Ruiz Medina

      Hi have the answer! :)
      I’ve tested in all kind of orgs and also confirmed by SF , JSREmoting calls don’t count agains API calls, the other posts that I read in internet are not correct. No more doubting now :)

      • http://blog.superpat.com/ Pat Patterson

        Correct – JavaScript Remoting does NOT count against API call limits, for the simple reason that it isn’t an API call :-) Please let me know any URLs that claim otherwise and I’ll do my best to correct them. Thanks for posting!

        • Carolina Ruiz Medina

          Hi Pat, sending them by email :) . Always thanks to you!