Sfdc

A ruby gem for the Salesforce REST api.

Features

  • A clean and modular architecture using Faraday middleware and Hashie::Mash‘d responses.
  • Support for interacting with multiple users from different orgs.
  • Support for parent-to-child relationships.
  • Support for aggregate queries.
  • Support for the Streaming 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!)
  • Support for Chatter

Installation

Add this line to your application’s Gemfile:

gem 'sfdc'

And then execute:

$ bundle

Or install it yourself as:

$ gem install sfdc

Usage

Sfdc 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').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 orgs 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.

OAuth Token Authentication

ruby client = Sfdc.new :instance_url => 'xx.salesforce.com', :oauth_token => '...'

Although the above will work, you’ll probably want to take advantage of the (re)authentication middleware by specifying a refresh token, client id and client secret:

ruby client = Sfdc.new :instance_url => 'xx.salesforce.com', :oauth_token => '...', :refresh_token => '...', :client_id => '...', :client_secret => '...'

Username/Password authentication

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

ruby client = Sfdc.new :username => '[email protected]', :password => '...', :security_token => '...', :client_id => '...', :client_secret => '...'

You can also set the username, password, security token, client id and client secret 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"

ruby client = Sfdc.new

Proxy Support

You can specify a http proxy using the :proxy_uri option, as follows:

ruby client = Sfdc.new :proxy_uri => 'http://proxy.example.com:123'

This paramter also will accept http://user@password:proxy.example.com:123 or using the environemnt variable PROXY_URI.

Sandbox Orgs

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

ruby client = Sfdc.new :host => 'test.salesforce.com' The host can also be set with the environment variable SALESFORCE_HOST.

Global Configuration

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

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


query

```ruby accounts = client.query(“select Id, Something__c from Account where Id = ‘someid’”) # => #<Sfdc::Collection >

account = accounts.first # => #<Sfdc::SObject >

account.sobject_type # => ‘Account’

account.Id # => “someid”

account.Name = ‘Foobar’ account.save # => true

account.destroy # => true ```

find

```ruby client.find(‘Account’, ‘001D000000INjVe’) # => #<Sfdc::SObject Id=”001D000000INjVe” Name=”Test” LastModifiedBy=”005G0000002f8FHIAY” … >

client.find(‘Account’, ‘1234’, ‘Some_External_Id_Field__c’) # => #<Sfdc::SObject Id=”001D000000INjVe” Name=”Test” LastModifiedBy=”005G0000002f8FHIAY” … > ```

```ruby # Find all occurrences of ‘bar’ client.search(‘FIND bar’) # => #<Sfdc::Collection >

Find accounts match the term ‘genepoint’ and return the Name field

client.search(‘FIND genepoint RETURNING Account (Name)’).map(&:Name) # => [‘GenePoint’] ```

create

ruby client.create('Account', Name: 'Foobar Inc.') # => '0016000000MRatd'

update

ruby client.update('Account', Id: '0016000000MRatd', Name: 'Whizbang Corp') # => true

upsert

ruby client.upsert('Account', 'External__c', External__c: 12, Name: 'Foobar') # => true

destroy

ruby client.destroy('Account', '0016000000MRatd') # => true

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.

describe

ruby client.describe # => { ... } client.describe('Account') # => { ... }

describe_layouts

ruby client.describe_layout('Account') # => { ... } client.describe_layouts('Account', '012E0000000RHEp') # => { ... }

picklist_values

```ruby client.picklist_values(‘Account’, ‘Type’) # => [#<Sfdc::Mash label=”Prospect” value=”Prospect”>]

Given a custom object named Automobile__c

# with picklist fields Model__c and Make__c, # where Model__c depends on the value of Make__c. client.picklist_values(‘Automobile__c’, ‘Model__c’, :valid_for => ‘Honda’) # => [#<Sfdc::Mash label=”Civic” value=”Civic”>, … ] ```

Chatter

ruby client.post_chatter('text', 'url')


authenticate!

Performs an authentication and returns the response. In general, calling this directly shouldn’t be required, since the client will handle authentication for you automatically. This should only be used if you want to sfdc an authentication before using the streaming api, or you want to get some information about the user.

```ruby response = client.authenticate! # => #<Sfdc::Mash access_token=”…” id=”https://login.salesforce.com/id/00DE0000000cOGcMAM/005E0000001eM4LIAU” instance_url=”https://na9.salesforce.com” issued_at=”1348465359751” scope=”api refresh_token” signature=”3fW0pC/TEY2cjK5FCBFOZdjRtCfAuEbK1U74H/eF+Ho=”>

Get the user information

info = client.get(response.id).body info.user_id # => ‘005E0000001eM4LIAU’ ```

File Uploads

Using the new Blob Data api feature (500mb limit):

ruby image = Sfdc::UploadIO.new(File.expand_path('image.jpg', __FILE__), 'image/jpeg') client.create 'Document', FolderId: '00lE0000000FJ6H', Description: 'Document test', Name: 'My image', Body: image)

Using base64-encoded data (37.5mb limit):

ruby data = Base64::encode64(File.read('image.jpg') client.create 'Document', FolderId: '00lE0000000FJ6H', Description: 'Document test', Name: 'My image', Body: data)

See also: http://www.salesforce.com/us/developer/docs/api_rest/Content/dome_sobject_insert_update_blob.htm

Downloading Attachments

Sfdc also makes it incredibly easy to download Attachments:

ruby attachment = client.query('select Id, Name, Body from Attachment').first File.open(attachment.Name, 'wb') { |f| f.write(attachment.Body) }

Custom Apex REST endpoints

You can use Sfdc to interact with your custom REST endpoints, by using .get, .put, .patch, .post, and .delete.

For example, if you had the following Apex REST endpoint on Salesforce:

```apex @RestResource(urlMapping=’/FieldCase/*’) global class RESTCaseController { @HttpGet global static List getOpenCases() { String companyName = RestContext.request.params.get('company'); Account company = [ Select ID, Name, Email__c, BillingState from Account where Name = :companyName];

List<Case> cases = [SELECT Id, Subject, Status, OwnerId, Owner.Name from Case WHERE AccountId = :company.Id];
return cases;   } } ```

…then you could query the cases using Sfdc:

ruby client.get '/services/apexrest/FieldCase', :company => 'GenePoint' # => #<Sfdc::Collection ...>


Streaming

Sfdc supports the Streaming API, and makes implementing pub/sub with Salesforce a trivial task:

```ruby # Sfdc uses faye as the underlying implementation for CometD. require ‘faye’

Initialize a client with your username/password/oauth token/etc.

client = Sfdc.new :username => ‘foo’, :password => ‘bar’, :security_token => ‘security token’ :client_id => ‘client_id’, :client_secret => ‘client_secret’

Create a PushTopic for subscribing to Account changes.

client.create! ‘PushTopic’, { ApiVersion: ‘23.0’, Name: ‘AllAccounts’, Description: ‘All account records’, NotifyForOperations: ‘All’, NotifyForFields: ‘All’, Query: “select Id from Account” }

EM.run { # Subscribe to the PushTopic. client.subscribe ‘AllAccounts’ do |message| puts message.inspect end } ```

See also: http://www.salesforce.com/us/developer/docs/api_streaming/index.htm


Caching

The gem supports easy caching of GET requests (e.g. queries):

```ruby # rails example: client = Sfdc.new cache: Rails.cache

or

Sfdc.configure do |config| config.cache = Rails.cache end ```

If you enable caching, you can disable caching on a per-request basis by using .without_caching:

ruby client.without_caching do client.query('select Id from Account') end

Logging / Debugging / Instrumenting

You can inspect what Sfdc is sending/receiving by setting Sfdc.log = true.

ruby Sfdc.log = true client = Sfdc.new.query('select Id, Name from Account')

Another awesome feature about sfdc is that, because it is based on Faraday, you can insert your own middleware.

For example, if you were using Sfdc in a Rails app, you can setup custom reporting to Librato using ActiveSupport::Notifications:

ruby client = Sfdc.new do |builder| builder.insert_after Sfdc::Middleware::InstanceURL, FaradayMiddleware::Instrumentation, name: 'request.salesforce' end

config/initializers/notifications.rb

ruby ActiveSupport::Notifications.subscribe('request.salesforce') do |*args| event = ActiveSupport::Notifications::Event.new(*args) Librato.increment 'api.salesforce.request.total' Librato.timing 'api.salesforce.request.time', event.duration end

force.com Canvas

You can use Sfdc to decode signed requests from Salesforce. See the example app.

Tooling API

To use the Tooling API, call Sfdc.tooling instead of Sfdc.new:

ruby client = Sfdc.tooling(...)


## License

Sfdc is available under the MIT license. See the LICENSE file for more info.