With the Salesforce hackathon fast approaching, I wanted to give a quick overview on building apps that use the force.com APIs (part of the Salesforce1 platform).
The force APIs are rich and varied, so sometimes just getting started can seem a little daunting.
What services are provided?
The force.com APIs give your application access to the authentication, data storage, and business rule services provided by the Salesforce1 platform. Some of the things you can do with the APIs include:
- Authenticate users based on a Salesforce username and password
- Query any data stored in a Salesforce account. Data access rules for the authenticated user are automatically applied.
- Create or update records in a Salesforce account. Data access rules for the authenticated user are automatically applied.
- Perform a free text search across all records in an account.
- Store and retrieve your own application-specific data in the Salesforce account.
This list covers the "core" force.com APIs. There are additional APIs for other services, and higher level access tools including Apex and Visualforce which are beyond our scope here.
Web application patterns
The Salesforce1 platform supports two primary architectures for building integrated web applications:
- Salesforce1 "native" applications using Apex and Visualforce, or Javascript + HTML.
- Connected applications which integrate via the SOAP or REST API
In the first case, you write your application code in the Apex language and use the Visualforce framework to build your web pages. You don't run any web or application servers yourself - all your code runs in the force.com environment. You can also implement single-page apps using AngularJS, Ember or something similar where your Javascript is served by force.com.
In the second case, you write your application code in any language you choose, and deploy your code to your own web and application servers (or deploy to a cloud host like Heroku). Your application integrates with force.com by making HTTP calls on the SOAP or REST APIs. This pattern is more flexible, but leaves you with more choices to make and more work to do.
Mobile application patterns
Because mobile apps introduce their own native-client environments, the choices for building mobile apps on Salesforce1 are a little more varied.
Build a hybrid app extension to the Salesforce1 app. Using Javascript and HTML, you can build new mobile pages which appear inside the Salesforce1 native app available for iOS and Android. User authentication comes for free since the user has authenticated into the Salesforce1 app. This corresponds most closely with our web pattern number 1 above. The result is: HTML+Javascript front-end, force.com back-end.
Build a native mobile app on iOS or Android, and use the force.com APIs directly in the mobile client by using the Salesforce iOS or Android SDKs. Users are authenticated with individual force.com logins. This is: native front-end, force.com back-end.
Build a native or hybrid mobile app which talks to a web application that itself uses the force.com APIs. All use of the force APIs is done server-side, and your client just talks to your custom API. Typically user accounts are stored in your application, and you use a single "API user" to access force.com. This corresponds to our web pattern number 2 above. We can call this the "force.com proxy" model.
Getting started
The following instructions will be useful if you want to build and deploy a Connected App which talks to the force.com APIs. If you are interested in building an app directly on Salesforce1, checkout the Force.com Workbook Tutorial for help getting started.
Before writing any code, I recommend that people try out the force.com APIs to get a sense of how they work. First, register for a free "Developer Edition" Salesforce account: https://developer.salesforce.com/. These trial accounts are free but include full API access and all developer tools.
Now open a tool called the Salesforce Workbench:
https://workbench.developerforce.com/login.php
The workbench makes it very easy to browse the Salesforce data model and all the Salesforce APIs. Your developer account will have preset data that you can query and modify.
Authentication
The first step to using any of the force.com APIs is to authenticate in to Salesforce. There are two primary mechanisms to do this:
Oauth web flow. This is an Oauth2 standard flow. Use this mechanism when each user of your app will have their own Salesforce login.
Password + token login. If you are using the "single API user" approach, then the simplest authentication approach is to send a username and password to the API login endpoint. For increased security however it isn't sufficient to provide just the password. You also need to present a 'security token'. Login to Salesforce with your API user account, then go to My Settings -> Personal -> Reset My Security Token and click the green button. Salesforce will send you a security token by email.
Accessing the API
There are a variety of SDKs that make accessing the Force.com APIs very easy. Pick a library that works with your language and get it installed.
For the examples below I will show a Ruby example, using the Restforce library, and a Node.js example using the Nforce library.
You can install one of these as follows:
$ gem install restforce
$ npm install nforce
To connect to Salesforce you need to define a Connected App in your Salesforce account. Follow these instructions to create your Connect App. The Connected App creates an Oauth consumer key and secret which you need to authenticate to the force.com API.
Note that even though you create a Connected App inside of one Salesforce account, your app can access any Salesforce acccount using the same Oauth credentials.
Gather the following pieces of information for accessing the Force.com API:
- Oauth consumer key
- Oauth consumer secret
- Oauth redirect URI
- API user username
- API user password
- API user security token
A good practice is to set all of these values in the environment for your app. On Heroku you can set config vars ('heroku config:set name=value') for these values.
Note that if you are using the "API user" pattern, then the Oauth redirect URI can be any value that you want, but it must match the value you entered into the Connected App.
Now, we are actually in position to authenticate into Force.com:
Ruby example
require 'restforce'
client = Restforce.new :username => 'foo',
:password => 'bar',
:security_token => 'security token',
:client_id => ENV['SF_OAUTH_CLIENT_ID'],
:client_secret => ENV['SF_OAUTH_CLIENT_SECRET']
Node example
var nforce = require('nforce');
var org = nforce.createConnection({
clientId: process.env('SF_OAUTH_CLIENT_ID'),
clientSecret: process.env('SF_OAUTH_CLIENT_SECRET'),
redirectUri: 'http://localhost:3000/oauth/_callback'
});
org.authenticate({ username: username, password: password + token}, function(err, resp){
// Use 'org' ...
});
Reading data
Salesforce data follows a relational model. Instead of 'table' however, Salesforce refers to 'objects', such as 'Contact' and 'Account'. One row from the table is referred to as an "instance" or more typically a "record".
Reading data is very easy. Force.com supports a simplified varient of SQL called SOQL. Let's see how to read 20 Account records from Salesforce:
Ruby example
accounts = client.query("select Id, Name, AccountNumber from Account limit 20")
Node example
var accounts = org.query({ query: 'select Id, Name, AccountNumber from Account limit 20' }, function(err, resp){
if(!err && resp.records) {
resp.records.forEach(function(account) {
console.log(account.get('Name'));
});
}
Writing data
To write new records, just create an empty object of the correct type and save it.
Ruby example
client.create('Account', Name: 'Foobar Inc.', AccountNumber: 'ACT101')
Node example
var acc = nforce.createSObject('Account');
acc.set('Name', 'Foobar Inc.');
acc.set('AccountNumer', 'ACT101');
org.insert({ sobject: acc }, function(err, resp){
if(!err) console.log('Account inserted');
});
Going further
The Heroku Mobile template provides a full example for accessing Force.com from your web server app.
Hopefully these instructions have gotten you started working with the Force.com APIs. There are lots of other resources out there with more information including the StackExchange group dedicated to Saleforce development.