A Ruby client for the Salesforce REST API.
Restforce is a ruby gem for the Salesforce REST API.
Features include:
Official Website | Documentation | Changelog
Add this line to your application's Gemfile:
gem 'restforce', '~> 8.0.1'And then execute:
$ bundleOr install it yourself as:
$ gem install restforceAs of version 8.0.0, this gem is only compatible with Ruby 3.1.0 and later. If you're using an earlier Ruby version:
This gem is versioned using Semantic Versioning, so you can be confident when updating that there will not be breaking changes outside of a major version (following format MAJOR.MINOR.PATCH, so for instance moving from 3.1.0 to 4.0.0 would be allowed to include incompatible API changes). See the changelog for details on what has changed in each version.
Restforce is designed with flexibility and ease of use in mind. By default, all API calls will
return Hashie::Mash objects,
so you can do things like client.query('select Id, (select Name from Children__r) from Account').first.Children__r.first.Name.
Which authentication method you use really depends on your use case. If you're building an application where many users from different organizations are authenticated through OAuth and you need to interact with data in their org on their behalf, you should use the OAuth token authentication method.
If you're using the gem to interact with a single org (maybe you're building some salesforce integration internally?) then you should use the username/password authentication method.
It is also important to note that the client object should not be reused across different threads, otherwise you may encounter thread-safety issues.
client = Restforce.new(oauth_token: 'access_token',
instance_url: 'instance url',
api_version: '41.0')Although the above will work, you'll probably want to take advantage of the (re)authentication middleware by specifying refresh_token, client_id, client_secret, and authentication_callback:
client = Restforce.new(oauth_token: 'access_token',
refresh_token: 'refresh token',
instance_url: 'instance url',
client_id: 'client_id',
client_secret: 'client_secret',
authentication_callback: Proc.new { |x| Rails.logger.debug x.to_s },
api_version: '41.0')The middleware will use the refresh_token automatically to acquire a new access_token if the existing access_token is invalid. The refresh process uses the host option so make sure that is set correctly for sandbox organizations.
authentication_callback is a proc that handles the response from Salesforce when the refresh_token is used to obtain a new access_token. This allows the access_token to be saved for re-use later - otherwise subsequent API calls will continue the cycle of "auth failure/issue new access_token/auth success".
The proc is passed one argument, a Hashie::Mash of the response from the Salesforce API:
{
"access_token" => "00Dx0000000BV7z!AR8AQP0jITN80ESEsj5EbaZTFG0RNBaT1cyWk7T5rqoDjoNIWQ2ME_sTZzBjfmOE6zMHq6y8PIW4eWze9JksNEkWUl.Cju7m4",
"signature" => "SSSbLO/gBhmmyNUvN18ODBDFYHzakxOMgqYtu+hDPsc=",
"scope" => "refresh_token full",
"instance_url" => "https://na1.salesforce.com",
"id" => "https://login.salesforce.com/id/00Dx0000000BV7z/005x00000012Q9P",
"token_type" => "Bearer",
"issued_at" => "1278448384422"
}The id field can be used to uniquely identify the user that the access_token and refresh_token belong to.
If you prefer to use a username and password to authenticate:
client = Restforce.new(username: config['username'],
password: config['password'],
instance_url: config['instance_url'],
host: config['host'], # test.salesforce.com for sandbox (optional)
client_id: config['client_key'], # Salesforce Client Key
client_secret: config['client_secret'], # Salesforce Client Secret
api_version: '55.0')If you prefer to use a JWT Bearer Token to authenticate:
client = Restforce.new(username: 'foo',
client_id: 'client_id',
instance_url: 'instance_url',
jwt_key: 'certificate_private_key',
api_version: '38.0')The jwt_key option is the private key of the certificate uploaded to your Connected App in Salesforce.
Choose "use digital signatures" in the Connected App configuration screen to upload your certificate.
You can also set the username, password, security token, client ID, client secret and API version in environment variables:
export SALESFORCE_USERNAME="username"
export SALESFORCE_PASSWORD="password"
export SALESFORCE_SECURITY_TOKEN="security token"
export SALESFORCE_CLIENT_ID="client id"
export SALESFORCE_CLIENT_SECRET="client secret"
export SALESFORCE_API_VERSION="41.0"client = Restforce.newNote: Restforce library does not cache JWT Bearer tokens automatically. This means that every instantiation of the Restforce class will be treated as a new login by Salesforce. Remember that Salesforce enforces rate limits on login requests. If you are building an application that will instantiate the Restforce class more than this specified rate limit, you might want to consider caching the Bearer token either in-memory or in your own storage by leveraging the authentication_callback method.
If you want to authenticate as an application, you can use the Client Credentials flow:
client = Restforce.new(client_id: 'client_id',
client_secret: 'client_secret',
api_version: '55.0',
host: 'MYDOMAIN.my.salesforce.com')You can connect to sandbox organizations by specifying a host. The default host is 'login.salesforce.com':
client = Restforce.new(host: 'test.salesforce.com')The host can also be set with the environment variable SALESFORCE_HOST.
You can specify a HTTP proxy using the proxy_uri option, as follows, or by setting the SALESFORCE_PROXY_URI environment variable:
client = Restforce.new(username: 'foo',
password: 'bar',
security_token: 'security token',
client_id: 'client_id',
client_secret: 'client_secret',
proxy_uri: 'http://proxy.example.com:123',
api_version: '41.0')You may specify a username and password for the proxy with a URL along the lines of 'http://user:[email protected]:123'.
You can set any of the options passed into Restforce.new globally:
Restforce.configure do |config|
config.client_id = 'foo'
config.client_secret = 'bar'
endBy default, the gem defaults to using Version 26.0 (Winter '13) of the Salesforce API. This maintains backwards compatibility for existing users.
We strongly suggest configuring Restforce to use the most recent API version, to get the best Salesforce API experience - for example, some more recently-added API endpoints will not be available without moving to a more recent
version. If you're trying to use a method that is unavailable with your API version,
Restforce will raise an APIVersionError.
There are three ways to set the API version:
api_version option when instantiating Restforce (i.e. Restforce.new(api_version: '41.0'))SALESFORCE_API_VERSION environment variable (i.e. export SALESFORCE_API_VERSION="41.0")Restforce.configure:Restforce.configure do |config|
config.api_version = '41.0'
# ...
endAll the CRUD methods (create, update, upsert, destroy) have equivalent methods with
a ! at the end (create!, update!, upsert!, destroy!), which can be used if you need
to do some custom error handling. The bang methods will raise exceptions, while the
non-bang methods will return false in the event that an exception is raised. This
works similarly to ActiveRecord.
Salesforce allows the addition of
custom headers
in REST API requests to trigger specific logic. In order to pass any custom headers along with API requests,
you can specify a hash of :request_headers upon client initialization. The example below demonstrates how
to include the sforce-auto-assign header in all client HTTP requests:
client = Restforce.new(oauth_token: 'access_token',
instance_url: 'instance url',
api_version: '41.0',
request_headers: { 'sforce-auto-assign' => 'FALSE' })
accounts = client.query("select Id, Something__c from Account where Id = 'someid'")
# => #
account = accounts.first
# => #
account.sobject_type
# => 'Account'
account.Id
# => "someid"
account.Name = 'Foobar'
account.save
# => true
account.destroy
# => trueaccounts =No open issues yet, or sync has not completed.