Salesforce REST library

Revision as of 17:49, 14 August 2026 by Lchrisman (talk | contribs) (Pin the Libraries folder path to release 7.1, the minimum this library requires)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)


Release:

 • 4.6 •  5.0 •  5.1 •  5.2 •  5.3 •  5.4 •   •  6.0 •  6.1 •  6.2 •  6.3 •  6.4 •  6.5 •  6.6 •  7.0 •  7.1 •  7.2

Requires Analytica 7.1 Analytica Developer edition or better.

The Salesforce REST library lets your model authenticate with Salesforce and read Salesforce records and metadata through the Salesforce REST API, version 67.0. Use it to pull live data -- accounts, contacts, opportunities, or your own custom objects -- straight into an Analytica model, so that your analysis works from current CRM data instead of an exported snapshot.

It provides:

  • OAuth 2.0 client-credentials authentication for unattended, server-to-server use
  • A legacy SOAP-login option as a temporary migration bridge
  • SOQL query execution, including automatic pagination
  • Record-selection and record-retrieval helpers
  • Salesforce object and field metadata
  • SOSL search

This library reads from Salesforce. It has no functions to create, update, or delete Salesforce records.

Download: Salesforce REST library.ana (v. 1.01)

Requirements

To use this library, you need:

  • Analytica 7.1 or later, Analytica Developer edition or better. The library is built on ReadFromUrl(), which is not available in the Professional or Player editions.
  • A Salesforce account, and an OAuth client configured in Salesforce (see Setting up Salesforce below).
  • Internet access allowing Analytica to reach your Salesforce login and instance domains over HTTPS. If you have a strong firewall, you may need to add a rule to allow this.

Getting started

  1. Download the library and save it into your "C:\Program Files\Lumina\Analytica 7.1\Libraries" folder.
  2. Launch Analytica and open your model, or start a new one.
  3. Select Add Library... from the File menu, select Salesforce REST library.ana, click OK, select Link, then click OK.

A typical model then uses three Variables -- an authentication Struct, a connection Struct, and one or more query results:

Variable Sf_auth ::= ClientCredentialsAuth(
        "https://login.salesforce.com",
        Sf_client_id,
        Sf_client_secret )

Variable Sf ::= Salesforce( Sf_auth )

Variable Active_accounts ::= SalesforceSelect( Sf, "Account", "Id, Name, Industry",
        where: "IsDeleted = false",
        order_by: "Name",
        row_limit: 100 )

Active_accounts is a query-result Struct. Its list of records is:

Active_accounts -> records

To read a field from the first record:

SalesforceField( Active_accounts -> records[@=1], "Name" )

When you authenticate to a sandbox, use "https://test.salesforce.com" in place of "https://login.salesforce.com".

A brief introduction to SOQL

Salesforce Object Query Language (SOQL) resembles SQL, but it queries Salesforce objects and fields by their API names rather than by table and column names. A basic query looks like this:

SELECT Id, Name, Industry
FROM Account
WHERE Industry = 'Technology'
ORDER BY Name
LIMIT 100

Standard object names include Account, Contact, and Opportunity. API names of custom objects and custom fields usually end in __c -- for example License__c or Expiration_Date__c. An object's API name is often not the same as the label you see in the Salesforce user interface, so use SalesforceObjects() and SalesforceFields() to discover the names you need.

Whenever you insert a text value into a SOQL expression, quote it with SalesforceSoqlQuote(). Don't use that function for object or field API names.

For the full language, see the Salesforce SOQL and SOSL Reference.

Setting up Salesforce for client-credentials authentication

ClientCredentialsAuth() is meant for unattended, server-to-server access. It needs an OAuth client configured in Salesforce, plus a dedicated Salesforce user whose permissions the integration runs under.

Salesforce terminology and Setup screens vary by edition and release. In current releases the OAuth client is normally an External Client App; some organizations still use a Connected App.

A Salesforce administrator generally needs to:

  1. Create an External Client App in Salesforce Setup.
  2. Enable OAuth settings and the OAuth 2.0 Client Credentials Flow.
  3. Grant the OAuth scope needed for REST access, normally Manage user data via APIs (api). Avoid broader scopes unless you need them.
  4. Save the app, then copy its Consumer Key and Consumer Secret. These become the «client_id» and «client_secret» parameters in Analytica.
  5. In the app's OAuth policies, select a dedicated Run As integration user for the client-credentials flow. Depending on the app type, Salesforce may also require Admin approved users are pre-authorized.
  6. Give the integration user the permissions your model needs -- API access, plus read access to the required objects and fields. Prefer permission sets and least privilege.
  7. If the app uses pre-authorization, assign the app's permission set or profile authorization to the integration user.

The library sends the token request to:

https://login.salesforce.com/services/oauth2/token

or, for a sandbox:

https://test.salesforce.com/services/oauth2/token

Salesforce returns an access token and the instance URL that the library uses for all later requests.

For current Salesforce-side details, see the Salesforce OAuth 2.0 Client Credentials Flow documentation.

Protect the client secret

The consumer secret grants access as the configured integration user. Don't save it in a model that you distribute to people who shouldn't have the credential, and don't commit it to source control. Where you can, obtain it at deployment time from your organization's approved secret-management mechanism.

Authentication and connection

ClientCredentialsAuth(login_url, client_id, client_secret)

Authenticates using the OAuth 2.0 client-credentials flow and returns a Struct holding the access token.

Parameter Meaning
«login_url» "https://login.salesforce.com" for production, or "https://test.salesforce.com" for a sandbox
«client_id» Consumer key from the Salesforce External Client App or Connected App
«client_secret» Consumer secret from the same app

The Struct it returns contains these members:

  • access_token
  • instance_url
  • status_code
  • status_text
  • raw_response

Example:

ClientCredentialsAuth( "https://login.salesforce.com", Sf_client_id, Sf_client_secret )

When authentication fails, it reports an Analytica error that includes the HTTP status and the Salesforce response.

Parameter types: ClientCredentialsAuth(login_url: Text; client_id: Text; client_secret: Text)

Salesforce(auth)

Creates the connection Struct that you pass to every query, record, search, and metadata function. «auth» is the Struct returned by ClientCredentialsAuth() or SoapLoginAuth().

The Struct it returns contains these members:

  • api_version -- "67.0"
  • instance_url
  • access_token
  • rest_base_url

Example:

Salesforce( Sf_auth )

It's usually clearer to define the authentication and the connection as separate Variables, as shown in Getting started, so that you can inspect an authentication failure on its own. You can also nest the calls:

Salesforce(
    ClientCredentialsAuth(
        "https://login.salesforce.com",
        Sf_client_id,
        Sf_client_secret ) )

All REST calls use API version 67.0, including calls authenticated through SoapLoginAuth().

Parameter types: Salesforce(auth)

SoapLoginAuth(login_url, username, password, security_token)

Logs in with the legacy Salesforce SOAP Partner API login() call and returns a Struct whose session ID the REST functions use as a bearer token.

«security_token» is the Salesforce security token for that user account. The function concatenates it onto the password, as SOAP login requires.

This authentication method is a migration bridge only. Salesforce retires the SOAP login() mechanism on 1-Jun-2027, after which this function stops working. Write new models against ClientCredentialsAuth(), and migrate existing ones before that date.

Parameter types: SoapLoginAuth(login_url: Text; username: Text; password: Text; security_token: Text)

Query functions

SalesforceSelect(sf, sobject, fields, where, order_by, row_limit)

Builds and runs a common SOQL SELECT. This is the easiest entry point when your query has a straightforward WHERE, ORDER BY, and LIMIT structure. It returns the same query-result Struct as SalesforceQuery().

Parameter Meaning
«sf» The connection returned by Salesforce()
«sobject» Salesforce object API name, such as "Account"
«fields» Comma-separated field API names
«where» Optional SOQL condition, without the WHERE keyword
«order_by» Optional ordering expression, without the ORDER BY keywords
«row_limit» Optional maximum number of records. 0, the default, applies no explicit limit

The three optional parameters are declared Named, so pass them by name:

SalesforceSelect( Sf, "Contact", "Id, Name, Email, Account.Name",
        where: "Email = " & SalesforceSoqlQuote( Target_email ),
        order_by: "Name",
        row_limit: 20 )

It validates the object and field API names, but «where» and «order_by» are SOQL fragments that you supply. Quote any text value you interpolate into them with SalesforceSoqlQuote(), as in the example above.

Parameter types: SalesforceSelect(sf; sobject: Text; fields: Text; where: Named Text := ""; order_by: Named Text := ""; row_limit: Named Number := 0)

SalesforceQuery(sf, soql, include_deleted, max_pages)

Runs a complete SOQL expression and follows Salesforce pagination until it has retrieved every page.

It returns a query-result Struct with these members:

Member Meaning
records List of parsed Salesforce record Structs
total_size Total matching records, as reported by Salesforce
pages Number of pages retrieved
done Whether Salesforce reported the query complete
next_records_url URL of a subsequent page. Normally Null once the query is complete
raw_response Raw response for the final page

Set «include_deleted» to True to use Salesforce's query-all behavior, which can include deleted and archived records where Salesforce supports it.

«max_pages», 100 by default, protects your model from an unexpectedly large or insufficiently bounded query. If the result needs more pages than this, it raises an error rather than quietly returning an incomplete result.

Example:

Local soql := "SELECT Id, Name, Amount, CloseDate " &
              "FROM Opportunity " &
              "WHERE IsClosed = false " &
              "ORDER BY CloseDate";
SalesforceQuery( Sf, soql )

Parameter types: SalesforceQuery(sf; soql: Text; include_deleted := False; max_pages: Number := 100)

SalesforceQueryFirst(sf, soql)

Runs a SOQL expression and returns the first matching record Struct, or Null when nothing matches. Include an ORDER BY clause whenever more than one record could match, so that you get a predictable result.

Example:

SalesforceQueryFirst( Sf,
    "SELECT Id, Name FROM Account WHERE Name = " &
    SalesforceSoqlQuote( Account_name ) &
    " ORDER BY LastModifiedDate DESC LIMIT 1" )

Parameter types: SalesforceQueryFirst(sf; soql: Text)

SalesforceCount(sf, soql, include_deleted)

Returns the query's totalSize as a number, so you don't have to retrieve and inspect the record list to count matches.

Example:

SalesforceCount( Sf, "SELECT Id FROM Opportunity WHERE IsClosed = false" )42

Parameter types: SalesforceCount(sf; soql: Text; include_deleted := False)

SalesforceQueryPage(sf, soql_or_next_url, include_deleted)

Retrieves exactly one query page. Pass a SOQL expression to get the first page, or the next_records_url from a previous result to get the page after it.

Most models should use SalesforceQuery(), which handles pagination for you. Use this function when your model deliberately needs page-by-page control.

Parameter types: SalesforceQueryPage(sf; soql_or_next_url: Text; include_deleted := False)

Record functions

SalesforceGetRecord(sf, sobject, record_id, fields)

Retrieves one record, given its Salesforce object API name and record ID. It returns the record Struct itself, not a query-result wrapper.

  • «record_id» must be a 15- or 18-character Salesforce ID.
  • «fields» is a comma-separated list of field API names.

Example:

SalesforceGetRecord( Sf, "Account", Account_id, "Id, Name, Industry, BillingCountry" )

Parameter types: SalesforceGetRecord(sf; sobject: Text; record_id: Text; fields: Text)

SalesforceGetRecords(sf, sobject, record_ids, fields)

Retrieves several records from a list of Salesforce record IDs, and returns a list of record Structs. Internally it builds a SOQL IN (...) condition from the IDs.

Example:

SalesforceGetRecords( Sf, "Contact", Contact_ids, "Id, Name, Email" )

Parameter types: SalesforceGetRecords(sf; sobject: Text; record_ids: List; fields: Text)

SalesforceField(record, field_path, default_value)

Reads a field from a Salesforce record Struct when the field name is a text value. A dotted «field_path» traverses relationship Structs.

Examples:

SalesforceField( Contact_record, "Email" )
SalesforceField( Contact_record, "Account.Name", "No account" )

It returns «default_value», Null by default, when the member is absent or it can't traverse the path.

When you already know the field name as you write the Definition, direct Struct access is simpler:

Contact_record -> Email

Use SalesforceField for dynamic field names, dotted paths, or when you want a controlled default.

Parameter types: SalesforceField(record; field_path: Text; default_value := Null)

Quoting text values

SalesforceSoqlQuote(value)

Escapes a text value as a SOQL string literal and surrounds it with single quotes, handling quotes, backslashes, and control characters.

Example:

"Name = " & SalesforceSoqlQuote( Customer_name )

If Customer_name is O'Reilly, this produces a valid quoted SOQL literal instead of letting the apostrophe terminate the value early.

Use this function for values only. You can't safely turn Salesforce object or field API names into identifiers by quoting them -- the library validates those names instead.

Array abstraction applies, so it also quotes a list of values. SalesforceGetRecords() relies on this when it builds its IN (...) condition.

Parameter types: SalesforceSoqlQuote(value: Text)

Metadata functions

These functions help you discover the API names and properties available to the authenticated integration user.

SalesforceObjects(sf)

Returns a list of summary Structs for the Salesforce objects that the authenticated user can see.

Example:

SalesforceObjects( Sf )

Useful members usually include the object's API name, its display label, and capability flags. Salesforce supplies the exact members, which vary by API release and object type.

Parameter types: SalesforceObjects(sf)

SalesforceDescribe(sf, sobject)

Returns Salesforce's full metadata description for an object, including its fields, relationships, picklist entries, and access capabilities.

Example:

SalesforceDescribe( Sf, "Opportunity" )

Parameter types: SalesforceDescribe(sf; sobject: Text)

SalesforceFields(sf, sobject)

Returns just the list of field metadata Structs from SalesforceDescribe(). Use it to find field API names, types, labels, whether a field can be filtered, and its allowed picklist values.

Example:

SalesforceFields( Sf, "Account" )

Parameter types: SalesforceFields(sf; sobject: Text)

Search

SalesforceSearch(sf, sosl)

Runs a Salesforce Object Search Language (SOSL) expression and returns its searchRecords list.

SOQL queries known objects and fields; SOSL searches text across one or more objects. Use SalesforceSearch when your search spans object types, or when it resembles a text search more than a structured query.

Example:

SalesforceSearch( Sf,
    "FIND {Acme} IN NAME FIELDS " &
    "RETURNING Account(Id, Name), Contact(Id, Name, Email)" )

For the full SOSL syntax, see the Salesforce SOQL and SOSL Reference.

Parameter types: SalesforceSearch(sf; sosl: Text)

Working with returned records

The library represents Salesforce JSON objects as Analytica Structs, and collections as lists. Given:

Variable Result ::= SalesforceSelect( Sf, "Account", "Id, Name, Owner.Name",
        where: "BillingCountry = " & SalesforceSoqlQuote( Country ),
        order_by: "Name",
        row_limit: 100 )

the records are:

Result -> records

the first record is:

Result -> records[@=1]

and you can read a field directly:

Result -> records[@=1] -> Name

or through the helper, which also handles the dotted relationship path:

SalesforceField( Result -> records[@=1], "Owner.Name" )

To build an array from the record list, introduce an Index for the record position and extract the members you want over that Index.

Error handling and troubleshooting

The library raises an Analytica error when authentication fails, when Salesforce returns an unsuccessful HTTP status, when a record ID is malformed, when an object or field API name is invalid, or when a query exceeds «max_pages».

Common causes:

Authentication fails
Check the login URL, the consumer key and secret, the client-credentials setting, the Run As user, and the app authorization.
INVALID_FIELD, or an unknown field
Use SalesforceFields() to check the field's API name. The display label is often not the API name.
Insufficient access
Check the integration user's API permission, object permissions, field-level security, sharing access, and permission-set assignments.
No records returned
Try a simpler query, confirm the integration user can see the records, and inspect total_size in the query-result Struct.
Query exceeds «max_pages»
Add a selective WHERE clause or a LIMIT. Raise «max_pages» only when you intend the larger transfer.
Sandbox authentication fails
Use "https://test.salesforce.com", unless your organization requires a specific My Domain login URL.
The network request fails
Confirm that the computer running Analytica reaches the Salesforce login and instance domains over HTTPS, and that any proxy or firewall permits the requests.

An HTTP 401 gets its own message asking you to recalculate the authentication and the connection, then retry -- the access token has expired or been revoked.

Function summary

Function Purpose
ClientCredentialsAuth() Authenticate with the OAuth 2.0 client-credentials flow
Salesforce() Create the REST connection Struct
SoapLoginAuth() Legacy SOAP authentication. Migrate before 1-Jun-2027
SalesforceSelect() Build and run a common SOQL SELECT
SalesforceQuery() Run complete SOQL and retrieve all pages
SalesforceQueryFirst() Return the first matching record, or Null
SalesforceCount() Return the total matching-record count
SalesforceQueryPage() Retrieve one query page manually
SalesforceGetRecord() Retrieve one record by ID
SalesforceGetRecords() Retrieve several records from a list of IDs
SalesforceField() Read a dynamic or dotted field path from a record
SalesforceSoqlQuote() Quote a text value safely for SOQL
SalesforceObjects() List the objects visible to the authenticated user
SalesforceDescribe() Retrieve full metadata for an object
SalesforceFields() List the field metadata for an object
SalesforceSearch() Run SOSL and return the search records

History

The Salesforce REST library was introduced in August 2026, and requires Analytica 7.1 or later. The Constant Salesforce_library_version in the library holds its version number, currently 1.01.

See also

Comments


You are not allowed to post comments.