API Reference

This section contains detailed API documentation for all modules and classes in Salesforce Toolkit.

Client Module

class sf_toolkit.client.AsyncSalesforceClient(login=None, token=None, token_refresh_callback=None, sync_parent=None)[source]

Bases: I_AsyncSalesforceClient

Parameters:
__init__(login=None, token=None, token_refresh_callback=None, sync_parent=None)[source]
Parameters:
unregister_parent()[source]
async request(method, url, resource_name='', **kwargs)[source]

Build and send a request.

Equivalent to:

`python request = client.build_request(...) response = await client.send(request, ...) `

See AsyncClient.build_request(), AsyncClient.send() and [Merging of configuration][0] for how the various parameters are merged with client-level configuration.

[0]: /advanced/clients/#merging-of-configuration

Parameters:
  • method (str)

  • url (URL | str)

  • resource_name (str)

Return type:

Response

async versions()[source]

Returns a dictionary of API versions available in the org asynchronously. https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/dome_versions.htm

Returns:

Dictionary of available API versions

Return type:

dict[float, ApiVersion]

class sf_toolkit.client.SalesforceClient(connection_name='default', login=None, token=None, token_refresh_callback=None, headers={'Accept': 'application/json'}, **kwargs)[source]

Bases: I_SalesforceClient

Parameters:
__init__(connection_name='default', login=None, token=None, token_refresh_callback=None, headers={'Accept': 'application/json'}, **kwargs)[source]
Parameters:
token_refresh_callback: Callable[[SalesforceToken], Any] | None
handle_async_clone_token_refresh(token)[source]
Parameters:

token (SalesforceToken)

property as_async: I_AsyncSalesforceClient
request(method, url, resource_name='', response_status_raise=True, **kwargs)[source]

Build and send a request.

Equivalent to:

`python request = client.build_request(...) response = client.send(request, ...) `

See Client.build_request(), Client.send() and [Merging of configuration][0] for how the various parameters are merged with client-level configuration.

[0]: /advanced/clients/#merging-of-configuration

Parameters:
  • method (str)

  • url (URL | str)

  • resource_name (str)

  • response_status_raise (bool)

Return type:

Response

property versions: dict[float, ApiVersion]

Returns a dictionary of API versions available in the org.

Returns:

List of available API versions

Return type:

list[ApiVersion]

Authentication

class sf_toolkit.auth.SalesforceAuth(login=None, session_token=None, callback=None)[source]

Bases: Auth

Parameters:
__init__(login=None, session_token=None, callback=None)[source]
Parameters:
auth_flow(request)[source]

Execute the authentication flow.

To dispatch a request, yield it:

` yield request `

The client will .send() the response back into the flow generator. You can access it like so:

` response = yield request `

A return (or reaching the end of the generator) will result in the client returning the last response obtained from the server.

You can dispatch as many requests as is necessary.

Parameters:

request (Request)

Return type:

Generator[Request, Response, None]

login: Callable[[], Generator[Request | None, Response | None, SalesforceToken]] | None
callback: Callable[[SalesforceToken], Any] | None
token: SalesforceToken | None
class sf_toolkit.auth.SalesforceToken(instance, token)[source]

Bases: NamedTuple

Create new instance of SalesforceToken(instance, token)

Parameters:
  • instance (URL)

  • token (str)

instance: URL

Alias for field number 0

token: str

Alias for field number 1

sf_toolkit.auth.lazy_login(**kwargs)[source]
sf_toolkit.auth.cli_login(alias_or_username=None, sf_exec_path=None)[source]
Parameters:
  • alias_or_username (str | None)

  • sf_exec_path (str | Path | None)

Return type:

Callable[[], Generator[Request | None, Response | None, SalesforceToken]]

sf_toolkit.auth.ip_filtering_non_service_login(username, password, client_id=None, domain='login', api_version=None)[source]
Parameters:
  • username (str)

  • password (str)

  • client_id (str | None)

  • domain (str)

  • api_version (float | int | None)

Return type:

Callable[[], Generator[Request | None, Response | None, SalesforceToken]]

sf_toolkit.auth.ip_filtering_org_login(username, password, organizationId, client_id=None, domain='login', api_version=None)[source]
Parameters:
  • username (str)

  • password (str)

  • organizationId (str)

  • client_id (str | None)

  • domain (str)

  • api_version (float | int | None)

Return type:

Callable[[], Generator[Request | None, Response | None, SalesforceToken]]

sf_toolkit.auth.security_token_login(username, password, security_token, client_id=None, domain='login', api_version=None)[source]
Parameters:
  • username (str)

  • password (str)

  • security_token (str)

  • client_id (str | None)

  • domain (str)

  • api_version (float | int | None)

Return type:

Callable[[], Generator[Request | None, Response | None, SalesforceToken]]

sf_toolkit.auth.lazy_soap_login(**kwargs)[source]

Infer which SOAP login flow should be used based on the parameters provided.

This function examines the kwargs to determine whether to use security_token_login, ip_filtering_org_login, or ip_filtering_non_service_login.

Parameters are the same as the underlying login functions, with required parameters determined by the login flow chosen.

Returns:

A callable that will perform the login workflow

Return type:

SalesforceLogin

sf_toolkit.auth.lazy_oauth_login(**kwargs)[source]

Determine which login method to use based on the provided kwargs.

sf_toolkit.auth.password_login(username, password, consumer_key, consumer_secret, domain='login')[source]

Process OAuth 2.0 Password Flow.

Parameters:
  • username (str)

  • password (str)

  • consumer_key (str)

  • consumer_secret (str)

  • domain (str)

Return type:

Callable[[], Generator[Request | None, Response | None, SalesforceToken]]

sf_toolkit.auth.public_key_auth_login(username, consumer_key, private_key, domain='login')[source]

Process OAuth 2.0 Public Key JWT Flow.

Parameters:
Return type:

Callable[[], Generator[Request | None, Response | None, SalesforceToken]]

sf_toolkit.auth.client_credentials_flow_login(consumer_key, consumer_secret, domain)[source]

Process OAuth 2.0 Client Credentials Flow.

Parameters:
  • consumer_key (str)

  • consumer_secret (str)

  • domain (str)

Return type:

Callable[[], Generator[Request | None, Response | None, SalesforceToken]]

class sf_toolkit.auth.types.SalesforceToken(instance, token)[source]

Bases: NamedTuple

Create new instance of SalesforceToken(instance, token)

Parameters:
  • instance (URL)

  • token (str)

instance: URL

Alias for field number 0

token: str

Alias for field number 1

class sf_toolkit.auth.httpx.SalesforceAuth(login=None, session_token=None, callback=None)[source]

Bases: Auth

Parameters:
__init__(login=None, session_token=None, callback=None)[source]
Parameters:
login: Callable[[], Generator[Request | None, Response | None, SalesforceToken]] | None
token: SalesforceToken | None
callback: Callable[[SalesforceToken], Any] | None
auth_flow(request)[source]

Execute the authentication flow.

To dispatch a request, yield it:

` yield request `

The client will .send() the response back into the flow generator. You can access it like so:

` response = yield request `

A return (or reaching the end of the generator) will result in the client returning the last response obtained from the server.

You can dispatch as many requests as is necessary.

Parameters:

request (Request)

Return type:

Generator[Request, Response, None]

sf_toolkit.auth.login_cli.cli_login(alias_or_username=None, sf_exec_path=None)[source]
Parameters:
  • alias_or_username (str | None)

  • sf_exec_path (str | Path | None)

Return type:

Callable[[], Generator[Request | None, Response | None, SalesforceToken]]

SObject Classes

class sf_toolkit.data.sobject.SObjectDescribe(*, name='', label='', labelPlural='', keyPrefix='', custom=False, customSetting=False, createable=False, updateable=False, deletable=False, undeletable=False, mergeable=False, queryable=False, feedEnabled=False, searchable=False, layoutable=False, activateable=False, fields=None, childRelationships=None, recordTypeInfos=None, **additional_properties)[source]

Bases: object

Represents metadata about a Salesforce SObject from a describe call

Parameters:
__init__(*, name='', label='', labelPlural='', keyPrefix='', custom=False, customSetting=False, createable=False, updateable=False, deletable=False, undeletable=False, mergeable=False, queryable=False, feedEnabled=False, searchable=False, layoutable=False, activateable=False, fields=None, childRelationships=None, recordTypeInfos=None, **additional_properties)[source]
Parameters:
classmethod from_dict(data)[source]

Create an SObjectDescribe instance from a dictionary (typically from a Salesforce API response)

Parameters:

data (dict)

Return type:

SObjectDescribe

get_field(field_name)[source]

Get the field metadata for a specific field by name

Parameters:

field_name (str)

Return type:

SObjectFieldDescribe | None

get_raw_data()[source]

Get the raw JSON data from the describe call

Return type:

dict

class sf_toolkit.data.sobject.SObject(_SObject__strict_fields=True, **fields)[source]

Bases: FieldConfigurableObject, I_SObject

Parameters:

_SObject__strict_fields (bool)

classmethod query(include_deleted=False)[source]

Create a new SoqlSelect query builder for this SObject type.

Parameters:

include_deleted (bool, optional) – Whether to include deleted records in the query. Defaults to False.

Returns:

A new query builder instance for this SObject type.

Return type:

SoqlSelect

Example

```python # Create a query builder for Contact query = Contact.select()

# Add conditions and execute the query result = query.query() ```

__init__(_SObject__strict_fields=True, **fields)[source]
Parameters:

_SObject__strict_fields (bool)

classmethod read(record_id, sf_client=None)[source]
Parameters:
  • record_id (str)

  • sf_client (I_SalesforceClient | None)

Return type:

_sObject

save_insert(sf_client=None, reload_after_success=False)[source]
Parameters:
  • sf_client (I_SalesforceClient | None)

  • reload_after_success (bool)

save_update(sf_client=None, only_changes=False, reload_after_success=False)[source]
Parameters:
  • sf_client (I_SalesforceClient | None)

  • only_changes (bool)

  • reload_after_success (bool)

save_upsert(external_id_field, sf_client=None, reload_after_success=False, update_only=False, only_changes=False)[source]
Parameters:
  • external_id_field (str)

  • sf_client (I_SalesforceClient | None)

  • reload_after_success (bool)

  • update_only (bool)

  • only_changes (bool)

save(sf_client=None, only_changes=False, reload_after_success=False, external_id_field=None, update_only=False)[source]
Parameters:
  • sf_client (I_SalesforceClient | None)

  • only_changes (bool)

  • reload_after_success (bool)

  • external_id_field (str | None)

  • update_only (bool)

delete(sf_client=None, clear_id_field=True)[source]
Parameters:
  • sf_client (I_SalesforceClient | None)

  • clear_id_field (bool)

reload(sf_client=None)[source]
Parameters:

sf_client (I_SalesforceClient | None)

update_values(**kwargs)[source]
classmethod list(*ids, sf_client=None, concurrency=1, on_chunk_received=None)[source]
Parameters:
  • ids (str)

  • sf_client (I_SalesforceClient | None)

  • concurrency (int)

  • on_chunk_received (Callable[[Response], None] | None)

Return type:

SObjectList

async classmethod read_async(*ids, sf_client=None, concurrency=1, on_chunk_received=None)[source]
Parameters:
  • ids (str)

  • sf_client (I_AsyncSalesforceClient | None)

  • concurrency (int)

  • on_chunk_received (Callable[[Response], Coroutine | None] | None)

Return type:

SObjectList

classmethod describe()[source]

Retrieves detailed metadata information about the SObject from Salesforce.

Returns:

The full describe result containing metadata about the SObject’s

fields, relationships, and other properties.

Return type:

dict

classmethod from_description(sobject, connection='')[source]

Build an SObject type definition for the named SObject based on the object ‘describe’ from Salesforce

Parameters:
  • sobject (str) – The API name of the SObject in Salesforce

  • connection (str) – The name of the Salesforce connection to use

Returns:

A dynamically created SObject subclass with fields matching the describe result

Return type:

type[SObject]

class sf_toolkit.data.sobject.SObjectList(iterable=(), *, connection='')[source]

Bases: list[_sObject], Generic[_sObject]

A list that contains SObject instances and provides bulk operations via Salesforce’s composite API.

Initialize an SObjectList.

Parameters:
  • iterable (Iterable[_sObject]) – An optional iterable of SObject instances

  • connection (str) – Optional name of the Salesforce connection to use

__init__(iterable=(), *, connection='')[source]

Initialize an SObjectList.

Parameters:
  • iterable (Iterable[_sObject]) – An optional iterable of SObject instances

  • connection (str) – Optional name of the Salesforce connection to use

append(item)[source]

Add an SObject to the list.

extend(iterable)[source]

Extend the list with an iterable of SObjects.

save(external_id_field=None, only_changes=False, concurrency=1, batch_size=200, all_or_none=False, update_only=False, **callout_options)[source]

Save all SObjects in the list, determining whether to insert, update, or upsert based on the records and parameters.

Parameters:
  • external_id_field (str | None) – Name of the external ID field to use for upserting (if provided)

  • only_changes (bool) – If True, only send changed fields for updates

  • concurrency (int) – Number of concurrent requests to make

  • batch_size (int) – Number of records to include in each batch

  • all_or_none (bool) – If True, all records must succeed or all will fail

  • update_only (bool) – If True with external_id_field, only update existing records

  • **callout_options – Additional options to pass to the API calls

Returns:

List of save results

Return type:

list[SObjectSaveResult]

save_insert(concurrency=1, batch_size=200, **callout_options)[source]

Insert all SObjects in the list. https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/resources_composite_sobjects_collections_create.htm

Returns:

The list of SObjectSaveResults indicating success or failure of each insert operation

Return type:

self

Parameters:
  • concurrency (int)

  • batch_size (int)

async static save_insert_async(sf_client, record_chunks, headers, concurrency, **callout_options)[source]
Parameters:
save_update(only_changes=False, concurrency=1, batch_size=200, **callout_options)[source]

Update all SObjects in the list.

Parameters:
  • only_changes (bool) – If True, only send changed fields

  • concurrency (int) – Number of concurrent requests to make

  • batch_size (int) – Number of records to include in each batch

  • **callout_options – Additional options to pass to the API call

Returns:

List of save results

Return type:

list[SObjectSaveResult]

async static save_update_async(record_chunks, headers, sf_client)[source]
Parameters:
Return type:

list[SObjectSaveResult]

save_upsert(external_id_field, concurrency=1, batch_size=200, only_changes=False, all_or_none=False, **callout_options)[source]

Upsert all SObjects in the list using an external ID field. https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/resources_composite_sobjects_collections_upsert.htm

Parameters:
  • external_id_field (str) – Name of the external ID field to use for upserting

  • concurrency (int) – Number of concurrent requests to make

  • batch_size (int) – Number of records to include in each batch

  • only_changes (bool) – If True, only send changed fields for updates

  • **callout_options – Additional options to pass to the API call

  • all_or_none (bool)

Returns:

List of save results

Return type:

list[SObjectSaveResult]

async static save_upsert_async(sf_client, url, record_chunks, headers, concurrency, all_or_none, **callout_options)[source]
Parameters:
delete(clear_id_field=False, batch_size=200, concurrency=1, all_or_none=False, **callout_options)[source]

Delete all SObjects in the list.

Parameters:
  • clear_id_field (bool) – If True, clear the ID field on the objects after deletion

  • batch_size (int)

  • concurrency (int)

  • all_or_none (bool)

Returns:

The list itself for method chaining

Return type:

self

async static delete_async(sf_client, record_id_batches, all_or_none, concurrency, **callout_options)[source]

Delete all SObjects in the list asynchronously.

Parameters:
  • sf_client (I_SalesforceClient) – The Salesforce client

  • record_id_batches (list[list[str]]) – List of batches of record IDs to delete

  • all_or_none (bool) – If True, delete all records or none

  • callout_options – Additional options for the callout

  • concurrency (int)

Returns:

List of SObjectSaveResult objects

Fields

exception sf_toolkit.data.fields.ReadOnlyAssignmentException[source]

Bases: TypeError

class sf_toolkit.data.fields.SObjectFieldDescribe(name, label, type, length=0, nillable=False, picklistValues=[], referenceTo=[], relationshipName=None, unique=False, updateable=False, createable=False, defaultValue=None, externalId=False, autoNumber=False, calculated=False, caseSensitive=False, dependentPicklist=False, deprecatedAndHidden=False, displayLocationInDecimal=False, filterable=False, groupable=False, permissionable=False, restrictedPicklist=False, sortable=False, writeRequiresMasterRead=False)[source]

Bases: NamedTuple

Represents metadata about a Salesforce SObject field

Create new instance of SObjectFieldDescribe(name, label, type, length, nillable, picklistValues, referenceTo, relationshipName, unique, updateable, createable, defaultValue, externalId, autoNumber, calculated, caseSensitive, dependentPicklist, deprecatedAndHidden, displayLocationInDecimal, filterable, groupable, permissionable, restrictedPicklist, sortable, writeRequiresMasterRead)

Parameters:
name: str

Alias for field number 0

label: str

Alias for field number 1

type: str

Alias for field number 2

length: int

Alias for field number 3

nillable: bool

Alias for field number 4

picklistValues: list[dict]

Alias for field number 5

referenceTo: list[str]

Alias for field number 6

relationshipName: str | None

Alias for field number 7

unique: bool

Alias for field number 8

updateable: bool

Alias for field number 9

createable: bool

Alias for field number 10

defaultValue: Any

Alias for field number 11

externalId: bool

Alias for field number 12

autoNumber: bool

Alias for field number 13

calculated: bool

Alias for field number 14

caseSensitive: bool

Alias for field number 15

dependentPicklist: bool

Alias for field number 16

deprecatedAndHidden: bool

Alias for field number 17

displayLocationInDecimal: bool

Alias for field number 18

filterable: bool

Alias for field number 19

groupable: bool

Alias for field number 20

permissionable: bool

Alias for field number 21

restrictedPicklist: bool

Alias for field number 22

sortable: bool

Alias for field number 23

writeRequiresMasterRead: bool

Alias for field number 24

class sf_toolkit.data.fields.MultiPicklistValue(source)[source]

Bases: str

Parameters:

source (str)

__init__(source)[source]
Parameters:

source (str)

values: list[str]
class sf_toolkit.data.fields.FieldFlag(value)[source]

Bases: Flag

nillable = 1
unique = 2
readonly = 4
case_sensitive = 8
updateable = 16
createable = 32
calculated = 64
filterable = 128
sortable = 256
groupable = 512
permissionable = 1024
restricted_picklist = 2048
display_location_in_decimal = 4096
write_requires_master_read = 8192
class sf_toolkit.data.fields.FieldConfigurableObject[source]

Bases: object

__init__()[source]
classmethod keys()[source]
Return type:

Iterable[str]

classmethod query_fields()[source]
Return type:

list[str]

property dirty_fields: set[str]
serialize(only_changes=False, all_fields=False)[source]
Parameters:
class sf_toolkit.data.fields.Field(py_type, *flags)[source]

Bases: Generic[T]

Parameters:
__init__(py_type, *flags)[source]
Parameters:
flags: set[FieldFlag]
revive(value)[source]
Parameters:

value (Any)

format(value)[source]
Parameters:

value (T)

Return type:

Any

validate(value)[source]
class sf_toolkit.data.fields.TextField(*flags)[source]

Bases: Field[str]

Parameters:

flags (set[FieldFlag])

__init__(*flags)[source]
Parameters:

flags (FieldFlag)

class sf_toolkit.data.fields.IdField(*flags)[source]

Bases: TextField

Parameters:

flags (set[FieldFlag])

validate(value)[source]
class sf_toolkit.data.fields.PicklistField(*flags, options=None)[source]

Bases: TextField

Parameters:
__init__(*flags, options=None)[source]
Parameters:
validate(value)[source]
Parameters:

value (str)

class sf_toolkit.data.fields.MultiPicklistField(*flags, options=None)[source]

Bases: Field[MultiPicklistValue]

Parameters:
__init__(*flags, options=None)[source]
Parameters:
revive(value)[source]
Parameters:

value (str)

validate(value)[source]
Parameters:

value (MultiPicklistValue)

class sf_toolkit.data.fields.NumberField(*flags)[source]

Bases: Field[float]

Parameters:

flags (set[FieldFlag])

__init__(*flags)[source]
Parameters:

flags (FieldFlag)

class sf_toolkit.data.fields.IntField(*flags)[source]

Bases: Field[int]

Parameters:

flags (set[FieldFlag])

__init__(*flags)[source]
Parameters:

flags (FieldFlag)

class sf_toolkit.data.fields.CheckboxField(*flags)[source]

Bases: Field[bool]

Parameters:

flags (set[FieldFlag])

__init__(*flags)[source]
Parameters:

flags (FieldFlag)

class sf_toolkit.data.fields.DateField(*flags)[source]

Bases: Field[date]

Parameters:

flags (set[FieldFlag])

__init__(*flags)[source]
Parameters:

flags (FieldFlag)

revive(value)[source]
Parameters:

value (date | str)

format(value)[source]
Parameters:

value (date)

class sf_toolkit.data.fields.TimeField(*flags)[source]

Bases: Field[time]

Parameters:

flags (set[FieldFlag])

__init__(*flags)[source]
Parameters:

flags (FieldFlag)

format(value)[source]
class sf_toolkit.data.fields.DateTimeField(*flags)[source]

Bases: Field[datetime]

Parameters:

flags (set[FieldFlag])

__init__(*flags)[source]
Parameters:

flags (FieldFlag)

revive(value)[source]
Parameters:

value (str)

format(value)[source]
class sf_toolkit.data.fields.ReferenceField(py_type, *flags)[source]

Bases: Field[T]

Parameters:
revive(value)[source]
class sf_toolkit.data.fields.ListField(item_type, *flags)[source]

Bases: Field[list[T]]

Parameters:
__init__(item_type, *flags)[source]
Parameters:
revive(value)[source]
Parameters:

value (list[dict | FieldConfigurableObject])

Query Builder

class sf_toolkit.data.query_builder.Comparison(prop, op, value)[source]

Bases: object

Parameters:
comparator: Literal['=', '!=', '<>', '>', '>=', '<', '<=', 'LIKE', 'INCLUDES', 'IN']
__init__(prop, op, value)[source]
Parameters:

prop (str)

prop: str
value: SoqlQuery | str | bool | datetime | date | None
sf_toolkit.data.query_builder.EQ(prop, value)[source]
Parameters:

prop (str)

sf_toolkit.data.query_builder.NE(prop, value)[source]
Parameters:

prop (str)

sf_toolkit.data.query_builder.GT(prop, value)[source]
Parameters:

prop (str)

sf_toolkit.data.query_builder.GE(prop, value)[source]
Parameters:

prop (str)

sf_toolkit.data.query_builder.LT(prop, value)[source]
Parameters:

prop (str)

sf_toolkit.data.query_builder.LE(prop, value)[source]
Parameters:

prop (str)

sf_toolkit.data.query_builder.LIKE(prop, value)[source]
Parameters:

prop (str)

sf_toolkit.data.query_builder.INCLUDES(prop, value)[source]
Parameters:

prop (str)

sf_toolkit.data.query_builder.IN(prop, value)[source]
Parameters:

prop (str)

sf_toolkit.data.query_builder.NOT_IN(prop, value)[source]
Parameters:

prop (str)

class sf_toolkit.data.query_builder.BooleanOperation(operator, conditions)[source]

Bases: object

Parameters:
__init__(operator, conditions)[source]
Parameters:
operator: Literal['AND', 'OR', 'NOT']
conditions: list[Comparison | BooleanOperation | str]
sf_toolkit.data.query_builder.OR(*conditions)[source]
Parameters:

conditions (Comparison | BooleanOperation | str)

sf_toolkit.data.query_builder.AND(*conditions)[source]
Parameters:

conditions (Comparison | BooleanOperation | str)

class sf_toolkit.data.query_builder.NOT(condition)[source]

Bases: BooleanOperation

Parameters:

condition (Comparison | BooleanOperation | str)

__init__(condition)[source]
Parameters:

condition (Comparison | BooleanOperation | str)

class sf_toolkit.data.query_builder.Order(field, direction)[source]

Bases: NamedTuple

Create new instance of Order(field, direction)

Parameters:
field: str

Alias for field number 0

direction: Literal['ASC', 'DESC']

Alias for field number 1

class sf_toolkit.data.query_builder.QueryResultBatch(sobject_type, /, done=True, totalSize=0, records=None, nextRecordsUrl=None, connection=None)[source]

Bases: Generic[_SObject]

A generic class to represent results returned by the Salesforce SOQL Query API.

done
Type:

bool

totalSize
Type:

int

records
Type:

list[T]

nextRecordsUrl
Type:

str, optional

Initialize a QueryResult object from Salesforce API response data.

Parameters:
  • **kwargs – Key-value pairs from the Salesforce API response.

  • sobject_type (type[_SObject])

  • done (bool)

  • totalSize (int)

  • records (list[_SObject])

  • nextRecordsUrl (str | None)

  • connection (SalesforceClient | None)

done: bool

Indicates whether all records have been retrieved (True) or if more batches exist (False)

totalSize: int

The total number of records that match the query criteria

records: list[_SObject]

The list of records returned by the query

nextRecordsUrl: str | None

URL to the next batch of records, if more exist

query_locator: str | None = None
batch_size: int | None = None
__init__(sobject_type, /, done=True, totalSize=0, records=None, nextRecordsUrl=None, connection=None)[source]

Initialize a QueryResult object from Salesforce API response data.

Parameters:
  • **kwargs – Key-value pairs from the Salesforce API response.

  • sobject_type (type[_SObject])

  • done (bool)

  • totalSize (int)

  • records (list[SObjectRecordJSON] | None)

  • nextRecordsUrl (str | None)

  • connection (SalesforceClient | None)

query_more()[source]
async query_more_async()[source]
class sf_toolkit.data.query_builder.QueryResult(*batches)[source]

Bases: Generic[_SObject]

Parameters:

batches (list[QueryResultBatch[_SObject]])

batch_index: int = 0
record_index: int = 0
__init__(*batches)[source]
Parameters:

batches (QueryResultBatch[_SObject])

batches: list[QueryResultBatch[_SObject]]
total_size: int
property done
as_list()[source]
Return type:

SObjectList[_SObject]

copy()[source]

Perform a shallow copy of the QueryResult object.

Return type:

QueryResult[_SObject]

class sf_toolkit.data.query_builder.SoqlQuery(sobject_type, include_deleted=False)[source]

Bases: Generic[_SObject]

Parameters:
  • sobject_type (type[_SObject])

  • include_deleted (bool)

__init__(sobject_type, include_deleted=False)[source]
Parameters:
  • sobject_type (type[_SObject])

  • include_deleted (bool)

sobject_type: type[_SObject]
property fields
filter_subqueries(**subqueries)[source]

Configure Parent-To-Child Relationship queries

By default, all records are returned in the subquery (no filtering).

https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_relationships_query_using.htm

Parameters:

**subqueries (SoqlQuery) – A dictionary of field names and SoqlQuery objects.

Returns:

The current SoqlQuery object.

Return type:

self

property sobject_name: str
classmethod build_conditional(arg, value)[source]
Parameters:

arg (str)

Return type:

Comparison | NOT

classmethod build_conditional_clause(kwargs, mode='all')[source]
Parameters:
Return type:

Comparison | BooleanOperation

where(_raw=None, _mode='all', **kwargs)[source]
Parameters:
and_where(_raw=None, _mode='all', **kwargs)[source]
Parameters:
or_where(_raw=None, _mode='all', **kwargs)[source]
Parameters:
group_by(*fields)[source]
Parameters:

fields (str)

having(_raw=None, _mode='all', **kwargs)[source]
Parameters:
and_having(_raw=None, _mode='all', **kwargs)[source]
Parameters:
or_having(_raw=None, _mode='all', **kwargs)[source]
Parameters:
limit(limit)[source]
Parameters:

limit (int)

offset(offset)[source]
Parameters:

offset (int)

order_by(*orders, **kw_orders)[source]
Parameters:
format(fields=None)[source]
Parameters:

fields (list[str] | None)

count()[source]

Executes a count query instead of fetching records. Returns the count of records that match the query criteria.

Returns:

Number of records matching the query criteria

Return type:

int

execute(*_fields)[source]

Executes the SOQL query and returns the first batch of results (up to 2000 records).

Parameters:

_fields (str)

Return type:

QueryResult[_SObject]

API Models

class sf_toolkit.apimodels.ApiVersion(version, label, url)[source]

Bases: object

Data structure representing a Salesforce API version. https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/resources_versions.htm

Initialize an ApiVersion object.

Parameters:
  • version (float) – The API version number as a float

  • label (str) – The display label for the API version

  • url (str) – The URL for accessing this API version

__init__(version, label, url)[source]

Initialize an ApiVersion object.

Parameters:
  • version (float | str) – The API version number as a float

  • label (str) – The display label for the API version

  • url (str) – The URL for accessing this API version

version: float
label: str
url: str
classmethod lazy_build(value)[source]
Return type:

ApiVersion

class sf_toolkit.apimodels.OrgLimit(name, max_value, current_value)[source]

Bases: object

Data structure representing a Salesforce Org Limit. https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/resources_limits.htm

Initialize an OrgLimit object.

Parameters:
  • name (str) – The name of the limit

  • max_value (int) – The maximum allowed value for this limit

  • current_value (int) – The current consumption value for this limit

__init__(name, max_value, current_value)[source]

Initialize an OrgLimit object.

Parameters:
  • name (str) – The name of the limit

  • max_value (int) – The maximum allowed value for this limit

  • current_value (int) – The current consumption value for this limit

remaining()[source]

Calculate the remaining capacity for this limit.

Returns:

The difference between max_value and current_value

Return type:

int

usage_percentage()[source]

Calculate the percentage of the limit that has been used.

Returns:

The percentage of the limit used as a float between 0 and 100

Return type:

float

is_critical(threshold=90.0)[source]

Determine if the limit usage exceeds a critical threshold.

Parameters:

threshold (float) – The percentage threshold to consider critical (default: 90%)

Returns:

True if usage percentage exceeds the threshold, False otherwise

Return type:

bool

class sf_toolkit.apimodels.UserInfo(user_id, name, email, organization_id, sub, email_verified, given_name, family_name, zoneinfo, photos, profile, picture, address, urls, active, user_type, language, locale, utcOffset, updated_at, preferred_username, **kwargs)[source]

Bases: object

Data structure representing user information returned from the Salesforce OAuth2 userinfo endpoint. https://help.salesforce.com/s/articleView?id=sf.remoteaccess_using_userinfo_endpoint.htm

Initialize a UserInfo object.

Parameters:
  • user_id (str) – The user’s Salesforce ID

  • name (str) – The user’s full name

  • email (str) – The user’s email address

  • organization_id (str) – The organization’s Salesforce ID

  • sub (str) – Subject identifier

  • email_verified (bool) – Whether the email has been verified

  • given_name (str) – The user’s first name

  • family_name (str) – The user’s last name

  • zoneinfo (str) – The user’s timezone (e.g., “America/Los_Angeles”)

  • photos (dict[str, str]) – Dictionary of profile photos (picture, thumbnail)

  • profile (str) – URL to the user’s profile

  • picture (str) – URL to the user’s profile picture

  • address (dict) – Dictionary containing address information

  • urls (dict[str, str]) – Dictionary of various API endpoints for this user

  • active (bool) – Whether the user is active

  • user_type (str) – The type of user (e.g., “STANDARD”)

  • language (str) – The user’s language preference

  • locale (str) – The user’s locale setting

  • utcOffset (int) – The user’s UTC offset in milliseconds

  • updated_at (str) – When the user information was last updated

  • preferred_username (str) – The user’s preferred username (typically email)

  • **kwargs – Additional attributes from the response

__init__(user_id, name, email, organization_id, sub, email_verified, given_name, family_name, zoneinfo, photos, profile, picture, address, urls, active, user_type, language, locale, utcOffset, updated_at, preferred_username, **kwargs)[source]

Initialize a UserInfo object.

Parameters:
  • user_id (str) – The user’s Salesforce ID

  • name (str) – The user’s full name

  • email (str) – The user’s email address

  • organization_id (str) – The organization’s Salesforce ID

  • sub (str) – Subject identifier

  • email_verified (bool) – Whether the email has been verified

  • given_name (str) – The user’s first name

  • family_name (str) – The user’s last name

  • zoneinfo (str) – The user’s timezone (e.g., “America/Los_Angeles”)

  • photos (dict[str, str]) – Dictionary of profile photos (picture, thumbnail)

  • profile (str) – URL to the user’s profile

  • picture (str) – URL to the user’s profile picture

  • address (dict) – Dictionary containing address information

  • urls (dict[str, str]) – Dictionary of various API endpoints for this user

  • active (bool) – Whether the user is active

  • user_type (str) – The type of user (e.g., “STANDARD”)

  • language (str) – The user’s language preference

  • locale (str) – The user’s locale setting

  • utcOffset (int) – The user’s UTC offset in milliseconds

  • updated_at (str) – When the user information was last updated

  • preferred_username (str) – The user’s preferred username (typically email)

  • **kwargs – Additional attributes from the response

Exceptions

All exceptions for Salesforce Toolkit

exception sf_toolkit.exceptions.SalesforceError(response, resource_name)[source]

Bases: Exception

Base Salesforce API exception

Initialize the SalesforceError exception

SalesforceError is the base class of exceptions in salesforce-toolkit

Parameters:
  • url_path – Salesforce URL that was called

  • status – Status code of the error response

  • resource_name (str) – Name of the Salesforce resource being queried

  • content – content of the response

  • response (Response)

message = 'Unknown error occurred for {url_path}. Response content: {content}'
__init__(response, resource_name)[source]

Initialize the SalesforceError exception

SalesforceError is the base class of exceptions in salesforce-toolkit

Parameters:
  • url_path – Salesforce URL that was called

  • status – Status code of the error response

  • resource_name (str) – Name of the Salesforce resource being queried

  • content – content of the response

  • response (Response)

exception sf_toolkit.exceptions.SalesforceMoreThanOneRecord(response, resource_name)[source]

Bases: SalesforceError

Error Code: 300 The value returned when an external ID exists in more than one record. The response body contains the list of matching records.

Initialize the SalesforceError exception

SalesforceError is the base class of exceptions in salesforce-toolkit

Parameters:
  • url_path – Salesforce URL that was called

  • status – Status code of the error response

  • resource_name (str) – Name of the Salesforce resource being queried

  • content – content of the response

  • response (Response)

message = '({status_code}) More than one record for {url_path}. Response content: {content}'
exception sf_toolkit.exceptions.SalesforceRecordNotModifiedSince(response, resource_name)[source]

Bases: SalesforceError

Error Code: 304 The request content hasn’t changed since a specified date and time. The date and time is provided in a If-Modified-Since header.

Initialize the SalesforceError exception

SalesforceError is the base class of exceptions in salesforce-toolkit

Parameters:
  • url_path – Salesforce URL that was called

  • status – Status code of the error response

  • resource_name (str) – Name of the Salesforce resource being queried

  • content – content of the response

  • response (Response)

__init__(response, resource_name)[source]

Initialize the SalesforceError exception

SalesforceError is the base class of exceptions in salesforce-toolkit

Parameters:
  • url_path – Salesforce URL that was called

  • status – Status code of the error response

  • resource_name (str) – Name of the Salesforce resource being queried

  • content – content of the response

  • response (Response)

exception sf_toolkit.exceptions.SalesforceMalformedRequest(response, resource_name)[source]

Bases: SalesforceError

Error Code: 400 The request couldn’t be understood, usually because the JSON or XML body contains an error.

Initialize the SalesforceError exception

SalesforceError is the base class of exceptions in salesforce-toolkit

Parameters:
  • url_path – Salesforce URL that was called

  • status – Status code of the error response

  • resource_name (str) – Name of the Salesforce resource being queried

  • content – content of the response

  • response (Response)

message = '({status_code}) Malformed request {url_path}. Response content: {content}'
exception sf_toolkit.exceptions.SalesforceExpiredSession(response, resource_name)[source]

Bases: SalesforceError

Error Code: 401 The session ID or OAuth token used has expired or is invalid. The response body contains the message and errorCode.

Initialize the SalesforceError exception

SalesforceError is the base class of exceptions in salesforce-toolkit

Parameters:
  • url_path – Salesforce URL that was called

  • status – Status code of the error response

  • resource_name (str) – Name of the Salesforce resource being queried

  • content – content of the response

  • response (Response)

message = '({status_code}) Expired session for {url_path}. Response content: {content}'
exception sf_toolkit.exceptions.SalesforceRefusedRequest(response, resource_name)[source]

Bases: SalesforceError

Error Code: 403 The request has been refused. Verify that the logged-in user has appropriate permissions.

Initialize the SalesforceError exception

SalesforceError is the base class of exceptions in salesforce-toolkit

Parameters:
  • url_path – Salesforce URL that was called

  • status – Status code of the error response

  • resource_name (str) – Name of the Salesforce resource being queried

  • content – content of the response

  • response (Response)

message = '({status_code}) Request refused for {url_path}. Response content: {content}'
exception sf_toolkit.exceptions.SalesforceResourceNotFound(response, resource_name)[source]

Bases: SalesforceError

Error Code: 404 The requested resource couldn’t be found. Check the URI for errors, and verify that there are no sharing issues.

Initialize the SalesforceError exception

SalesforceError is the base class of exceptions in salesforce-toolkit

Parameters:
  • url_path – Salesforce URL that was called

  • status – Status code of the error response

  • resource_name (str) – Name of the Salesforce resource being queried

  • content – content of the response

  • response (Response)

exception sf_toolkit.exceptions.SalesforceMethodNotAllowedForResource(response, resource_name)[source]

Bases: SalesforceError

Error Code: 405 The method specified in the Request-Line isn’t allowed for the resource specified in the URI.

Initialize the SalesforceError exception

SalesforceError is the base class of exceptions in salesforce-toolkit

Parameters:
  • url_path – Salesforce URL that was called

  • status – Status code of the error response

  • resource_name (str) – Name of the Salesforce resource being queried

  • content – content of the response

  • response (Response)

message = '({status_code}) HTTP Method Not Allowed for {url_path}. Response content: {content}'
exception sf_toolkit.exceptions.SalesforceApiVersionIncompatible(response, resource_name)[source]

Bases: SalesforceError

Error Code: 409

The request couldn’t be completed due to a conflict with the current state of the resource. Check that the API version is compatible with the resource you’re requesting.

Initialize the SalesforceError exception

SalesforceError is the base class of exceptions in salesforce-toolkit

Parameters:
  • url_path – Salesforce URL that was called

  • status – Status code of the error response

  • resource_name (str) – Name of the Salesforce resource being queried

  • content – content of the response

  • response (Response)

message = '({status_code}) API Version incompatible for {url_path}. Response content: {content}'
exception sf_toolkit.exceptions.SalesforceResourceRemoved(response, resource_name)[source]

Bases: SalesforceError

Error Code: 410

The requested resource has been retired or removed. Delete or update any references to the resource.

Initialize the SalesforceError exception

SalesforceError is the base class of exceptions in salesforce-toolkit

Parameters:
  • url_path – Salesforce URL that was called

  • status – Status code of the error response

  • resource_name (str) – Name of the Salesforce resource being queried

  • content – content of the response

  • response (Response)

message = '({status_code}) Resource removed from {url_path}. Response content: {content}'
exception sf_toolkit.exceptions.SalesforceInvalidHeaderPreconditions(response, resource_name)[source]

Bases: SalesforceError

Error Code: 412

The request wasn’t executed because one or more of the preconditions that the client specified in the request headers wasn’t satisfied. For example, the request includes an If-Unmodified-Since header, but the data was modified after the specified date.

Initialize the SalesforceError exception

SalesforceError is the base class of exceptions in salesforce-toolkit

Parameters:
  • url_path – Salesforce URL that was called

  • status – Status code of the error response

  • resource_name (str) – Name of the Salesforce resource being queried

  • content – content of the response

  • response (Response)

message = '({status_code}) Invalid Header Preconditions for {url_path}. Response content: {content}'
exception sf_toolkit.exceptions.SalesforceUriLimitExceeded(response, resource_name)[source]

Bases: SalesforceError

Error Code: 414

The length of the URI exceeds the 16,384-byte limit.

Initialize the SalesforceError exception

SalesforceError is the base class of exceptions in salesforce-toolkit

Parameters:
  • url_path – Salesforce URL that was called

  • status – Status code of the error response

  • resource_name (str) – Name of the Salesforce resource being queried

  • content – content of the response

  • response (Response)

message = '({status_code}) URI Limit Exceeded for {url_path}. Response content: {content}'
exception sf_toolkit.exceptions.SalesforceUnsupportedFormat(response, resource_name)[source]

Bases: SalesforceError

Error Code: 415

The entity in the request is in a format that’s not supported by the specified method.

Initialize the SalesforceError exception

SalesforceError is the base class of exceptions in salesforce-toolkit

Parameters:
  • url_path – Salesforce URL that was called

  • status – Status code of the error response

  • resource_name (str) – Name of the Salesforce resource being queried

  • content – content of the response

  • response (Response)

message = '({status_code}) Unsupported Content Format for {url_path}. Response content: {content}'
exception sf_toolkit.exceptions.SalesforceEdgeRoutingUnavailable(response, resource_name)[source]

Bases: SalesforceError

Error Code: 420

Salesforce Edge doesn’t have routing information available for this request host. Contact Salesforce Customer Support.

Initialize the SalesforceError exception

SalesforceError is the base class of exceptions in salesforce-toolkit

Parameters:
  • url_path – Salesforce URL that was called

  • status – Status code of the error response

  • resource_name (str) – Name of the Salesforce resource being queried

  • content – content of the response

  • response (Response)

message = '({status_code}) Salesforce Edge Routing Unavailable for {url_path}. Response content: {content}'
exception sf_toolkit.exceptions.SalesforceMissingConditionalHeader(response, resource_name)[source]

Bases: SalesforceError

Error Code: 428 The request wasn’t executed because it wasn’t conditional. Add one of the Conditional Request Headers, such as If-Match, to the request and resubmit it.

Initialize the SalesforceError exception

SalesforceError is the base class of exceptions in salesforce-toolkit

Parameters:
  • url_path – Salesforce URL that was called

  • status – Status code of the error response

  • resource_name (str) – Name of the Salesforce resource being queried

  • content – content of the response

  • response (Response)

message = '({status_code}) Conditional Header Missing for {url_path}. Response content: {content}'
exception sf_toolkit.exceptions.SalesforceHeaderLimitExceeded(response, resource_name)[source]

Bases: SalesforceError

Error Code: 431

The combined length of the URI and headers exceeds the 16,384-byte limit.

Initialize the SalesforceError exception

SalesforceError is the base class of exceptions in salesforce-toolkit

Parameters:
  • url_path – Salesforce URL that was called

  • status – Status code of the error response

  • resource_name (str) – Name of the Salesforce resource being queried

  • content – content of the response

  • response (Response)

message = '({status_code}) URI and Header exceeded 16kb limit for {url_path}.Response content: {content}'
exception sf_toolkit.exceptions.SalesforceServerError(response, resource_name)[source]

Bases: SalesforceError

Error Code: 500

An error has occurred within Lightning Platform, so the request couldn’t be completed. Contact Salesforce Customer Support.

Initialize the SalesforceError exception

SalesforceError is the base class of exceptions in salesforce-toolkit

Parameters:
  • url_path – Salesforce URL that was called

  • status – Status code of the error response

  • resource_name (str) – Name of the Salesforce resource being queried

  • content – content of the response

  • response (Response)

message = '({status_code}) Salesforce Server Error for {url_path}. Response content: {content}'
exception sf_toolkit.exceptions.SalesforceEdgeCommFailure(response, resource_name)[source]

Bases: SalesforceError

Error Code: 502

Salesforce Edge wasn’t able to communicate successfully with the Salesforce instance.

Initialize the SalesforceError exception

SalesforceError is the base class of exceptions in salesforce-toolkit

Parameters:
  • url_path – Salesforce URL that was called

  • status – Status code of the error response

  • resource_name (str) – Name of the Salesforce resource being queried

  • content – content of the response

  • response (Response)

message = '({status_code}) Salesforce Edge Communication Failure for {url_path}. Response content: {content}'
exception sf_toolkit.exceptions.SalesforceServerUnavailable(response, resource_name)[source]

Bases: SalesforceError

Error Code: 503

The server is unavailable to handle the request. Typically this issue occurs if the server is down for maintenance or is overloaded.

Initialize the SalesforceError exception

SalesforceError is the base class of exceptions in salesforce-toolkit

Parameters:
  • url_path – Salesforce URL that was called

  • status – Status code of the error response

  • resource_name (str) – Name of the Salesforce resource being queried

  • content – content of the response

  • response (Response)

message = '({status_code}) Salesforce Server Unavailable for {url_path}. Response content: {content}'
exception sf_toolkit.exceptions.SalesforceAuthenticationFailed(code, message)[source]

Bases: Exception

Thrown to indicate that authentication with Salesforce failed.

__init__(code, message)[source]
exception sf_toolkit.exceptions.SalesforceGeneralError(response, resource_name)[source]

Bases: SalesforceError

A non-specific Salesforce error.

Initialize the SalesforceError exception

SalesforceError is the base class of exceptions in salesforce-toolkit

Parameters:
  • url_path – Salesforce URL that was called

  • status – Status code of the error response

  • resource_name (str) – Name of the Salesforce resource being queried

  • content – content of the response

  • response (Response)

exception sf_toolkit.exceptions.SalesforceOperationError[source]

Bases: Exception

Base error for Bulk API 2.0 operations

exception sf_toolkit.exceptions.SalesforceBulkV2LoadError[source]

Bases: SalesforceOperationError

Error occurred during bulk 2.0 load

exception sf_toolkit.exceptions.SalesforceBulkV2ExtractError[source]

Bases: SalesforceOperationError

Error occurred during bulk 2.0 extract

sf_toolkit.exceptions.raise_for_status(response, name='')[source]
Parameters:
  • response (Response)

  • name (str)

Utilities

Formatting helpers that perform quoting and escaping

class sf_toolkit.formatting.SoqlFormatter[source]

Bases: Formatter

Custom formatter to apply quoting or the :literal format spec

format_field(value, format_spec)[source]
sf_toolkit.formatting.format_soql(query, *args, **kwargs)[source]

Insert values quoted for SOQL into a format string

sf_toolkit.formatting.quote_soql_value(value)[source]

Quote/escape either an individual value or a list of values for a SOQL value expression

sf_toolkit.formatting.format_external_id(field, value)[source]

Create an external ID string for use with get() or upsert()

sf_toolkit.formatting.format_datetime(value)[source]

Get the provided datetime as a Salesforce-compliant formatted string

Parameters:

value (datetime)

sf_toolkit.formatting.parse_datetime(value)[source]

Parse a datetime from a Salesforce datetime string value

Parameters:

value (str)

Utility functions and types to assist in parsing API usage metadata

class sf_toolkit.metrics.Usage(used, total)[source]

Bases: NamedTuple

Create new instance of Usage(used, total)

Parameters:
used: int

Alias for field number 0

total: int

Alias for field number 1

class sf_toolkit.metrics.PerAppUsage(used, total, name)[source]

Bases: NamedTuple

Create new instance of PerAppUsage(used, total, name)

Parameters:
used: int

Alias for field number 0

total: int

Alias for field number 1

name: str

Alias for field number 2

class sf_toolkit.metrics.ApiUsage(api_usage, per_app_api_usage)[source]

Bases: NamedTuple

Create new instance of ApiUsage(api_usage, per_app_api_usage)

Parameters:
api_usage: Usage | None

Alias for field number 0

per_app_api_usage: PerAppUsage | None

Alias for field number 1

sf_toolkit.metrics.parse_api_usage(sforce_limit_info)[source]

Parse API usage and limits out of the Sforce-Limit-Info header Arguments: * sforce_limit_info: The value of response header ‘Sforce-Limit-Info’

Example 1: ‘api-usage=18/5000’ Example 2: ‘api-usage=25/5000;

per-app-api-usage=17/250(appName=sample-connected-app)’

Parameters:

sforce_limit_info (str)