Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
R

restforce

> 编程语言
Open source

A Ruby client for the Salesforce REST API.

823 stars0 likes4 views
WebsiteGitHub

About

A Ruby client for the Salesforce REST API.

Restforce

Restforce is a ruby gem for the Salesforce REST API.

Features include:

  • A clean and modular architecture using Faraday middleware and Hashie::Mash'd responses.
  • Support for interacting with multiple users from different organizations.
  • Support for parent-to-child relationships.
  • Support for aggregate queries.
  • Support for the Streaming API
  • Support for the Composite API
  • Support for the Composite Batch API
  • Support for the GetUpdated API
  • Support for blob data types.
  • Support for GZIP compression.
  • Support for custom Apex REST endpoints.
  • Support for dependent picklists.
  • Support for decoding Force.com Canvas signed requests. (NEW!)

Official Website | Documentation | Changelog

Installation

Add this line to your application's Gemfile:

gem 'restforce', '~> 8.0.1'

And then execute:

$ bundle

Or install it yourself as:

$ gem install restforce

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

  • for Ruby 3.0, use version 7.6.0 or earlier
  • for Ruby 2.7, use version 6.2.4 or earlier
  • for Ruby 2.6, use version 5.3.1 or earlier
  • for Ruby 2.5, use version 5.0.6 or earlier
  • for Ruby 2.4, use version 4.3.0 or earlier
  • for Ruby 2.3, use version 3.2.0 or earlier
  • for Ruby versions 2.2, 2.1 and 2.0, use version 2.5.3 or earlier
  • for Ruby 1.9.3, use version 2.4.2

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.

Usage

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.

Initialization

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.

OAuth token authentication

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

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

ruby
{
    "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.

Username/Password authentication

If you prefer to use a username and password to authenticate:

ruby
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')

JWT Bearer Token

If you prefer to use a JWT Bearer Token to authenticate:

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

bash
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"
ruby
client = Restforce.new

Note: 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.

Client Credentials

If you want to authenticate as an application, you can use the Client Credentials flow:

ruby
client = Restforce.new(client_id: 'client_id',
                       client_secret: 'client_secret',
                       api_version: '55.0',
                       host: 'MYDOMAIN.my.salesforce.com')

Sandbox Organizations

You can connect to sandbox organizations by specifying a host. The default host is 'login.salesforce.com':

ruby
client = Restforce.new(host: 'test.salesforce.com')

The host can also be set with the environment variable SALESFORCE_HOST.

Proxy Support

You can specify a HTTP proxy using the proxy_uri option, as follows, or by setting the SALESFORCE_PROXY_URI environment variable:

ruby
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'.

Global configuration

You can set any of the options passed into Restforce.new globally:

ruby
Restforce.configure do |config|
  config.client_id     = 'foo'
  config.client_secret = 'bar'
end

API versions

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

  • Passing in an api_version option when instantiating Restforce (i.e. Restforce.new(api_version: '41.0'))
  • Setting the SALESFORCE_API_VERSION environment variable (i.e. export SALESFORCE_API_VERSION="41.0")
  • Configuring the version globally with Restforce.configure:
ruby
Restforce.configure do |config|
  config.api_version = '41.0'
  # ...
end

Bang! methods

All 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.

Custom Headers

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:

ruby
client = Restforce.new(oauth_token: 'access_token',
                       instance_url: 'instance url',
                       api_version: '41.0',
                       request_headers: { 'sforce-auto-assign' => 'FALSE' })

query

ruby
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
# => true

query_all

ruby
accounts =

Issues· 174 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Ruby

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言