API reference¶
This reference is generated from the docstrings. The public, SemVer-covered surface is
every name in even_simpler_salesforce.__all__, plus the documented submodules
even_simpler_salesforce.testing, even_simpler_salesforce.observability,
even_simpler_salesforce.contrib.fastapi and even_simpler_salesforce.contrib.flask. Classes shown
here under private module paths (the objects returned by sf.sobject(), sf.collections,
sf.files, sf.ui, sf.auth, sf.actions, sf.apex, sf.leads and sf.platform_events) are public
through those attributes, not through their import path.
Salesforce is generated from AsyncSalesforce and has the same methods without async, so
only the async classes are shown in full.
The reasons behind the design are written down in the architecture decision records.
Clients¶
AsyncSalesforce
¶
AsyncSalesforce(
auth: Auth,
*,
api_version: str = DEFAULT_API_VERSION,
http_client: AsyncClient | None = None,
store: AsyncTokenStore | None = None,
cache: Cache | None = None,
observers: Iterable[Observer] = (),
budget: Budget | None = None,
retry: RetryPolicy | None = None,
timeout: Timeouts | None = None,
max_concurrency: int | None = None,
user_agent: str | None = None,
json: Any = None,
error_tags: Mapping[str, type[SalesforceError]]
| None = None,
cursor_key: bytes | None = None,
instance_url: str | None = None,
describe_cache: DescribeCacheConfig | None = None,
log_soql: Literal["hash", "redacted"] = "hash",
http2: bool = False,
client_name: str | None = None,
pubsub_endpoint: str | None = None,
default_namespace: str | None = None,
update_mru: bool | None = None,
)
Salesforce REST client. The async and sync clients share this API; the sync one is generated.
Example
auth = esf.ClientCredentials(domain="https://acme.my.salesforce.com", client_id="...", client_secret="...") async with esf.AsyncSalesforce(auth) as sf: lead = await sf.sobject("Lead").get("00Q...")
Clients are safe to share across tasks. with_auth() and tagged() return cheap
children that share the connection pool, caches, observers and usage counters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
auth
|
Auth
|
Login flow ( |
required |
api_version
|
str
|
Salesforce API version (pinned per library release; v59.0 or newer). |
DEFAULT_API_VERSION
|
http_client
|
AsyncClient | None
|
Inject your own |
None
|
store
|
AsyncTokenStore | None
|
Token store. Defaults to an in-memory store shared by the family. |
None
|
cache
|
Cache | None
|
Describe cache ( |
None
|
observers
|
Iterable[Observer]
|
Event observers (see |
()
|
budget
|
Budget | None
|
API usage budget and guard. |
None
|
retry
|
RetryPolicy | None
|
Retry policy. |
None
|
timeout
|
Timeouts | None
|
HTTP timeouts (ignored when |
None
|
max_concurrency
|
int | None
|
Max in-flight requests for the whole family. |
None
|
user_agent
|
str | None
|
|
None
|
json
|
Any
|
Object with |
None
|
error_tags
|
Mapping[str, type[SalesforceError]] | None
|
Map of |
None
|
cursor_key
|
bytes | None
|
HMAC key used to sign query cursors. |
None
|
instance_url
|
str | None
|
Override the instance URL learned from the token response (this client
and |
None
|
describe_cache
|
DescribeCacheConfig | None
|
Describe-cache settings. |
None
|
log_soql
|
Literal['hash', 'redacted']
|
|
'hash'
|
http2
|
bool
|
Enable HTTP/2 on the owned client (needs the |
False
|
client_name
|
str | None
|
Sent as |
None
|
pubsub_endpoint
|
str | None
|
|
None
|
default_namespace
|
str | None
|
Namespace prefix of a managed package, sent as
|
None
|
update_mru
|
bool | None
|
Sent as |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
An option is not valid, or |
usage
property
¶
API usage tracker; sf.usage.snapshot() returns a :class:UsageSnapshot.
The call counters are shared by the client family. The Sforce-Limit-Info values
and the budget guard use the org of this client's token.
api_version
property
¶
api_version: str
The Salesforce API version used for every URL (e.g. "68.0").
instance_url
property
¶
instance_url: str | None
Base URL of the org this client talks to (e.g. https://acme.my.salesforce.com).
The instance_url= override if one was given, else the instance of the current token;
None before the first call (no token yet). Read-only; no I/O. Use it to build links;
make calls with :meth:request.
observers
property
¶
The observer hub shared by the client family; sf.observers.add(obs) adds one.
aclose
async
¶
Close the owned HTTP client. No-op on children and for injected clients.
with_auth
¶
with_auth(
auth: Auth,
*,
store: AsyncTokenStore | None = None,
instance_url: str | None = None,
) -> AsyncSalesforce
A child client with its own auth, sharing pool, caches, observers and usage.
The parent's instance_url= override is not inherited (the child may be another
org); pass instance_url= here if the child needs one.
tagged
¶
tagged(
caller: str | None = None,
priority: Priority | None = None,
) -> AsyncSalesforce
A child view whose calls carry caller / priority (for logs, counters, budget).
sobject
¶
sobject(name: str) -> AsyncSObject
Operations on one sObject type, e.g. sf.sobject("Lead").get(id).
merge
async
¶
merge(
master_id: str,
duplicate_ids: Sequence[str],
*,
sobject: str,
) -> MergeResult
Merge up to two records into a master record (SOAP merge; REST has none).
Salesforce deletes the merged records and moves their related records to the master.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
master_id
|
str
|
The record to keep. |
required |
duplicate_ids
|
Sequence[str]
|
One or two records of the same object to merge into the master. |
required |
sobject
|
str
|
|
required |
Returns:
| Type | Description |
|---|---|
MergeResult
|
The master id, the merged ids and the related records that moved. |
Raises:
| Type | Description |
|---|---|
ValueError
|
unsupported |
RecordError
|
Salesforce refused the merge; the subclass follows the status code. |
describe_global
async
¶
GET sobjects: list of sObjects, served from the describe cache when fresh.
query
async
¶
query(
soql: str,
*values: Any,
page_size: int | None = None,
include_deleted: bool = False,
model: Any = None,
) -> QueryResult[Any]
Run SOQL and return one page plus a cursor.
Example
page = await sf.query("SELECT Id FROM Lead WHERE Email = {}", email)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
soql
|
str
|
The query. |
required |
*values
|
Any
|
Values for the |
()
|
page_size
|
int | None
|
|
None
|
include_deleted
|
bool
|
Use |
False
|
model
|
Any
|
Optional Pydantic model / dataclass for the rows. |
None
|
query_one
async
¶
Return exactly one row.
Reads only the first page and decides from totalSize; the SOQL is never rewritten.
Raises:
| Type | Description |
|---|---|
NotFound
|
no rows. |
MultipleMatches
|
more than one row ( |
query_first
async
¶
Return the first row, or None when there are none (never raises for no rows).
Reads only the first page; add LIMIT 1 yourself to avoid fetching more rows.
explain
async
¶
GET query?explain=: how Salesforce would run soql, without running it.
Returns the plans as Salesforce sends them (most optimal first). Salesforce labels the explain parameter a Beta feature.
query_more
async
¶
query_more(
cursor: Cursor | str,
*,
page_size: int | None = None,
model: Any = None,
) -> QueryResult[Any]
Fetch the page after cursor. Rejects tampered or foreign cursors.
Accepts cursors of sf.tooling.query too; the page then comes from the Tooling API.
query_iter
async
¶
query_iter(
soql: str,
*values: Any,
page_size: int | None = None,
include_deleted: bool = False,
model: Any = None,
expand_children: bool = False,
) -> AsyncIterator[Any]
Yield every row, fetching pages lazily.
values fill the {} placeholders as in :meth:query. With
expand_children=True, child subquery results that were truncated are followed to
completion before the parent row is yielded.
count
async
¶
Run SELECT COUNT() ... and return totalSize; values as in :meth:query.
search
async
¶
GET search?q=. Returns the matching records.
Wrap user input in :func:esf.sosl_term (f"FIND {esf.sosl_term(text)} ..."); SOQL
quoting does not apply to SOSL search terms.
parameterized_search
async
¶
parameterized_search(
q: str,
*,
sobjects: Sequence[str | Mapping[str, Any]]
| None = None,
fields: Sequence[str] | None = None,
limit: int | None = None,
**extra: Any,
) -> list[dict[str, Any]]
POST parameterizedSearch. sobjects items may be names or full spec dicts.
graphql
async
¶
POST graphql: run a GraphQL query and return its data member.
Example
data = await sf.graphql( "query Lead($id: ID) { uiapi { query { Lead(where: {Id: {eq: $id}}) " "{ edges { node { Id Name { value } } } } } } }", {"id": lead_id}, )
Queries are reads, so the client resends them after a timeout or a 5xx. A document
with a mutation is never resent after it may have reached Salesforce.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
The GraphQL document. |
required |
variables
|
Mapping[str, Any] | None
|
Values for the variables the document declares. |
None
|
Raises:
| Type | Description |
|---|---|
GraphQLError
|
the response has an |
graphql_iter
async
¶
graphql_iter(
query: str,
variables: Mapping[str, Any] | None = None,
*,
path: str,
) -> AsyncIterator[Any]
Yield every node of a GraphQL connection, fetching pages lazily.
Example
async for lead in sf.graphql_iter(query, path="uiapi.query.Lead"): print(lead["Id"])
The query must declare an $after variable and pass it to the connection, and must
select pageInfo { hasNextPage endCursor }. The client sets after to
endCursor for each next page and yields each edges[].node.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
A GraphQL document with exactly one query that declares |
required |
variables
|
Mapping[str, Any] | None
|
Values for the other variables (an |
None
|
path
|
str
|
Dotted path from |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
the query doesn't declare |
GraphQLError
|
a page has an |
UnexpectedResponse
|
|
run
async
¶
run(action: Action[R]) -> R
Run a typed action stub (written by esf generate actions) and return its result.
Example
result = await sf.run(AssignLead(lead_id="00Q..."))
The inputs are the stub's fields; fields set to None are not sent. The output values
become the stub's result type (a dataclass or a Pydantic model).
Raises:
| Type | Description |
|---|---|
SalesforceError
|
the typed error of the failed invocation, as for
|
request
async
¶
request(
method: str,
path: str,
*,
params: Mapping[str, Any] | None = None,
json: Any = None,
content: bytes | None = None,
headers: Mapping[str, str] | None = None,
idempotent: bool | None = None,
operation: str = "raw",
) -> Any
Call any REST resource through the full pipeline (auth, refresh, retries, errors, logs).
path is relative to /services/data/vXX.X/ or absolute under /services/.
Returns decoded JSON, None for an empty body, str for a text body (text/*,
XML, or any charset=) and bytes for anything else, such as
ContentVersion/{id}/VersionData file contents.
limits
async
¶
GET limits: every org limit. Costs one API call; never called implicitly.
start_limits_poller
¶
start_limits_poller(
interval: float = MIN_LIMITS_POLL_INTERVAL,
) -> None
Opt-in: poll GET limits every interval seconds (min 300) to refresh usage.
Each poll costs one API call. Stopped when the root client closes.
With AsyncSalesforce call this from inside a running event loop; Salesforce uses a
daemon thread.
Salesforce
¶
Salesforce(
auth: Auth,
*,
api_version: str = DEFAULT_API_VERSION,
http_client: Client | None = None,
store: TokenStore | None = None,
cache: Cache | None = None,
observers: Iterable[Observer] = (),
budget: Budget | None = None,
retry: RetryPolicy | None = None,
timeout: Timeouts | None = None,
max_concurrency: int | None = None,
user_agent: str | None = None,
json: Any = None,
error_tags: Mapping[str, type[SalesforceError]]
| None = None,
cursor_key: bytes | None = None,
instance_url: str | None = None,
describe_cache: DescribeCacheConfig | None = None,
log_soql: Literal["hash", "redacted"] = "hash",
http2: bool = False,
client_name: str | None = None,
pubsub_endpoint: str | None = None,
default_namespace: str | None = None,
update_mru: bool | None = None,
)
Salesforce REST client. The async and sync clients share this API; the sync one is generated.
Example
auth = esf.ClientCredentials(domain="https://acme.my.salesforce.com", client_id="...", client_secret="...") with esf.Salesforce(auth) as sf: lead = sf.sobject("Lead").get("00Q...")
Clients are safe to share across tasks. with_auth() and tagged() return cheap
children that share the connection pool, caches, observers and usage counters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
auth
|
Auth
|
Login flow ( |
required |
api_version
|
str
|
Salesforce API version (pinned per library release; v59.0 or newer). |
DEFAULT_API_VERSION
|
http_client
|
Client | None
|
Inject your own |
None
|
store
|
TokenStore | None
|
Token store. Defaults to an in-memory store shared by the family. |
None
|
cache
|
Cache | None
|
Describe cache ( |
None
|
observers
|
Iterable[Observer]
|
Event observers (see |
()
|
budget
|
Budget | None
|
API usage budget and guard. |
None
|
retry
|
RetryPolicy | None
|
Retry policy. |
None
|
timeout
|
Timeouts | None
|
HTTP timeouts (ignored when |
None
|
max_concurrency
|
int | None
|
Max in-flight requests for the whole family. |
None
|
user_agent
|
str | None
|
|
None
|
json
|
Any
|
Object with |
None
|
error_tags
|
Mapping[str, type[SalesforceError]] | None
|
Map of |
None
|
cursor_key
|
bytes | None
|
HMAC key used to sign query cursors. |
None
|
instance_url
|
str | None
|
Override the instance URL learned from the token response (this client
and |
None
|
describe_cache
|
DescribeCacheConfig | None
|
Describe-cache settings. |
None
|
log_soql
|
Literal['hash', 'redacted']
|
|
'hash'
|
http2
|
bool
|
Enable HTTP/2 on the owned client (needs the |
False
|
client_name
|
str | None
|
Sent as |
None
|
pubsub_endpoint
|
str | None
|
|
None
|
default_namespace
|
str | None
|
Namespace prefix of a managed package, sent as
|
None
|
update_mru
|
bool | None
|
Sent as |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
An option is not valid, or |
AsyncSObject
¶
AsyncSObject(
client: AsyncSalesforce, name: str, *, base: str = ""
)
Operations on one sObject type. Get one with sf.sobject("Lead").
sf.tooling.sobject("ApexClass") returns the same class for a Tooling API object: its
paths start with tooling/ and its operation names with tooling..
get
async
¶
get(
record_id: str,
fields: Sequence[str] | None = None,
*,
model: None = None,
if_modified_since: None = None,
) -> dict[str, Any]
get(
record_id: str,
fields: Sequence[str] | None = None,
*,
model: None = None,
if_modified_since: datetime,
) -> dict[str, Any] | None
get(
record_id: str,
fields: Sequence[str] | None = None,
*,
model: Any = None,
if_modified_since: datetime | None = None,
) -> Any
GET sobjects/{o}/{id}. With if_modified_since, returns None on 304.
get_by_external_id
async
¶
get_by_external_id(
field: str,
value: str,
fields: Sequence[str] | None = None,
*,
model: Any = None,
) -> Any
GET sobjects/{o}/{field}/{value}: the record whose external id field is value.
Salesforce reads a path that ends in .json, .xml or .html as a response
format, so it can't find a record whose value ends like that. For such values the client
finds the id with SELECT Id ... WHERE field = value and then reads the record with
GET sobjects/{o}/{id}: two requests, the same result and the same errors. The
fallback is for REST API objects only: a Tooling object (sf.tooling.sobject) always
sends the value in the path, because the fallback isn't verified for the Tooling API.
Raises:
| Type | Description |
|---|---|
NotFound
|
No record has this value. |
MultipleMatches
|
Several records have it (the field isn't unique). |
describe
async
¶
GET sobjects/{o}/describe, served from the describe cache when fresh.
updated
async
¶
GET sobjects/{o}/updated?start=&end=: ids updated in the window.
deleted
async
¶
GET sobjects/{o}/deleted?start=&end=: ids deleted in the window.
create
async
¶
create(
data: Mapping[str, Any],
*,
assignment_rule_id: str | bool | None = None,
duplicate_rules: DuplicateRules | None = None,
allow_save: bool | None = None,
) -> str
POST sobjects/{o}. Returns the new record id.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Mapping[str, Any]
|
Field values. |
required |
assignment_rule_id
|
str | bool | None
|
|
None
|
duplicate_rules
|
DuplicateRules | None
|
|
None
|
allow_save
|
bool | None
|
Deprecated (removed in 0.7): use
|
None
|
Raises:
| Type | Description |
|---|---|
DuplicateDetected
|
A duplicate rule blocked the record, or alerted without
|
TypeError
|
Both |
update
async
¶
update(
record_id: str,
data: Mapping[str, Any],
*,
assignment_rule_id: str | bool | None = None,
duplicate_rules: DuplicateRules | None = None,
allow_save: bool | None = None,
if_unmodified_since: datetime | None = None,
) -> None
PATCH sobjects/{o}/{id}. if_unmodified_since → :class:Conflict on 412.
A key set to None is sent as JSON null and clears the field; a key left out of
data keeps its value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
record_id
|
str
|
The record to change. |
required |
data
|
Mapping[str, Any]
|
Field values. |
required |
assignment_rule_id
|
str | bool | None
|
|
None
|
duplicate_rules
|
DuplicateRules | None
|
|
None
|
allow_save
|
bool | None
|
Deprecated (removed in 0.7): use
|
None
|
if_unmodified_since
|
datetime | None
|
Send |
None
|
Raises:
| Type | Description |
|---|---|
Conflict
|
The record changed after |
TypeError
|
Both |
upsert
async
¶
upsert(
field: str,
value: str,
data: Mapping[str, Any],
*,
assignment_rule_id: str | bool | None = None,
duplicate_rules: DuplicateRules | None = None,
allow_save: bool | None = None,
) -> UpsertResult
PATCH sobjects/{o}/{field}/{value}: update the matching record, or create one.
For a value that ends in .json, .xml or .html (which Salesforce reads as a
response format in a path), the client sends the same upsert as one record through
PATCH composite/sobjects/{o}/{field} instead. The result and the errors are the same.
A Tooling object (sf.tooling.sobject) always sends the value in the path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
field
|
str
|
The external id field. |
required |
value
|
str
|
The external id value. |
required |
data
|
Mapping[str, Any]
|
Field values. |
required |
assignment_rule_id
|
str | bool | None
|
|
None
|
duplicate_rules
|
DuplicateRules | None
|
|
None
|
allow_save
|
bool | None
|
Deprecated (removed in 0.7): use
|
None
|
Raises:
| Type | Description |
|---|---|
MultipleMatches
|
Several records have this value (HTTP 300). |
InvalidField
|
|
TypeError
|
Both |
delete
async
¶
delete(record_id: str) -> None
DELETE sobjects/{o}/{id}.
Takes no conditional headers: Salesforce doesn't support them on DELETE
(REST API Developer Guide, Conditional Request Headers). Sent anyway, an
If-Unmodified-Since makes Salesforce reject the request (500 UNKNOWN_EXCEPTION,
or 400 BAD_HEADER for a future date) and keep the record.
AsyncCollections
¶
AsyncCollections(
client: AsyncSalesforce, concurrency: int = 4
)
Many records per round trip. Results keep the input order.
With all_or_none=True each chunk of 200 is atomic, but chunks are separate
transactions: when a later chunk fails, earlier chunks are already committed. Chunks
then run one at a time and the first failing chunk raises a typed error.
create
async
¶
create(
rows: Iterable[Mapping[str, Any]],
*,
sobject: str | None = None,
all_or_none: bool = False,
concurrency: int | None = None,
assignment_rule_id: str | bool | None = None,
duplicate_rules: DuplicateRules | None = None,
allow_save: bool | None = None,
) -> BatchResult[RecordResult]
POST composite/sobjects in chunks of 200. Rows need attributes.type or sobject=.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rows
|
Iterable[Mapping[str, Any]]
|
Field values, one mapping per record. |
required |
sobject
|
str | None
|
The sObject type of rows without |
None
|
all_or_none
|
bool
|
Roll back a chunk when one of its rows fails. |
False
|
concurrency
|
int | None
|
Chunks in flight at once (default: the client's setting). |
None
|
assignment_rule_id
|
str | bool | None
|
|
None
|
duplicate_rules
|
DuplicateRules | None
|
|
None
|
allow_save
|
bool | None
|
Deprecated (removed in 0.7): use
|
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
Both |
update
async
¶
update(
sobject: str,
rows: Iterable[Mapping[str, Any]],
*,
all_or_none: bool = False,
concurrency: int | None = None,
assignment_rule_id: str | bool | None = None,
duplicate_rules: DuplicateRules | None = None,
allow_save: bool | None = None,
) -> BatchResult[RecordResult]
PATCH composite/sobjects in chunks of 200. Each row needs Id.
A key set to None clears the field; a key left out keeps its value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sobject
|
str
|
The sObject type of every row. |
required |
rows
|
Iterable[Mapping[str, Any]]
|
Field values with the |
required |
all_or_none
|
bool
|
Roll back a chunk when one of its rows fails. |
False
|
concurrency
|
int | None
|
Chunks in flight at once (default: the client's setting). |
None
|
assignment_rule_id
|
str | bool | None
|
|
None
|
duplicate_rules
|
DuplicateRules | None
|
|
None
|
allow_save
|
bool | None
|
Deprecated (removed in 0.7): use
|
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
Both |
upsert
async
¶
upsert(
sobject: str,
field: str,
rows: Iterable[Mapping[str, Any]],
*,
all_or_none: bool = False,
concurrency: int | None = None,
assignment_rule_id: str | bool | None = None,
duplicate_rules: DuplicateRules | None = None,
allow_save: bool | None = None,
) -> BatchResult[RecordResult]
PATCH composite/sobjects/{o}/{field} in chunks of 200.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sobject
|
str
|
The sObject type of every row. |
required |
field
|
str
|
The external id field that matches rows to records; each row sets it. |
required |
rows
|
Iterable[Mapping[str, Any]]
|
Field values, one mapping per record. |
required |
all_or_none
|
bool
|
Roll back a chunk when one of its rows fails. |
False
|
concurrency
|
int | None
|
Chunks in flight at once (default: the client's setting). |
None
|
assignment_rule_id
|
str | bool | None
|
|
None
|
duplicate_rules
|
DuplicateRules | None
|
|
None
|
allow_save
|
bool | None
|
Deprecated (removed in 0.7): use
|
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
Both |
delete
async
¶
delete(
ids: Iterable[str],
*,
all_or_none: bool = False,
concurrency: int | None = None,
) -> BatchResult[RecordResult]
DELETE composite/sobjects?ids= in chunks of 200.
AsyncFiles
¶
AsyncFiles(client: AsyncSalesforce)
Salesforce Files: upload, download and share ContentVersion files.
Uploads and downloads are streamed. The client never holds a whole file in memory, so files up to the 2 GB ContentVersion limit work.
upload
async
¶
upload(
source: bytes
| str
| PathLike[str]
| IO[bytes]
| AsyncIterable[bytes],
*,
filename: str | None = None,
title: str | None = None,
link_to: str | None = None,
share_type: ShareType | None = None,
visibility: Visibility | None = None,
) -> str
Upload a file as a new ContentVersion. Returns the ContentVersion id.
The client sends a multipart POST sobjects/ContentVersion and streams the file
content, so memory use stays at about one chunk whatever the file size.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
bytes | str | PathLike[str] | IO[bytes] | AsyncIterable[bytes]
|
The file content: |
required |
filename
|
str | None
|
File name stored as |
None
|
title
|
str | None
|
Title shown in Salesforce. Defaults to |
None
|
link_to
|
str | None
|
Record id to share the file with. Without |
None
|
share_type
|
ShareType | None
|
|
None
|
visibility
|
Visibility | None
|
|
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
no file name, an invalid id, or |
SalesforceError
|
Salesforce rejected the upload or the link. If only the link failed, the message names the uploaded ContentVersion id. |
Example
cv_id = await sf.files.upload("invoice.pdf", link_to=account_id)
download
async
¶
download(
content_version_id: str,
) -> AsyncIterator[AsyncFileStream]
Stream the content of a ContentVersion: GET sobjects/ContentVersion/{id}/VersionData.
Use it as a context manager and iterate over the stream for bytes chunks. The
connection closes when the block ends, also if you stop reading early.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
content_version_id
|
str
|
Id of the ContentVersion ( |
required |
Raises:
| Type | Description |
|---|---|
NotFound
|
no such ContentVersion, or no access to it. |
TransportError
|
the connection failed while you read the stream. |
Example
async with sf.files.download(cv_id) as stream: async for chunk in stream: out.write(chunk)
download_bytes
async
¶
The whole content of a ContentVersion as bytes.
This reads the file into memory. Use :meth:download for large files.
download_attachment
async
¶
The content of a legacy Attachment (GET sobjects/Attachment/{id}/Body) as bytes.
link
async
¶
link(
content_document_id: str,
record_id: str,
*,
share_type: ShareType = "V",
visibility: Visibility | None = None,
) -> str
Share a file with a record: create a ContentDocumentLink. Returns the link id.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
content_document_id
|
str
|
Id of the ContentDocument ( |
required |
record_id
|
str
|
Record, user, group or library to link the file to. |
required |
share_type
|
ShareType
|
|
'V'
|
visibility
|
Visibility | None
|
|
None
|
AsyncFileStream
¶
The body of a file download, read chunk by chunk. You get one from sf.files.download().
Iterate over it once to get bytes chunks. The connection stays open until the
async with block of sf.files.download() ends; the sf.request event for the
download is emitted then, with the number of bytes read.
Attributes:
| Name | Type | Description |
|---|---|---|
content_type |
str | None
|
|
content_length |
int | None
|
Size in bytes from |
aclose
async
¶
Close the connection and emit the sf.request event. Safe to call twice.
AsyncBulk
¶
AsyncBulk(client: AsyncSalesforce)
Bulk API 2.0: load or read large numbers of records with asynchronous jobs.
Uploads and query results are streamed, so memory use stays flat whatever the data size.
ingest
async
¶
ingest(
sobject: str,
operation: IngestOperation,
*,
rows: Iterable[Mapping[str, Any]]
| str
| PathLike[str]
| bytes,
external_id_field: str | None = None,
line_ending: LineEnding = "LF",
column_delimiter: ColumnDelimiter = "COMMA",
columns: Sequence[str] | None = None,
) -> AsyncIngestJob
Create an ingest job, upload the data and mark the upload complete.
Salesforce then processes the job in the background. The client splits data over 100 MB into several jobs, as Salesforce advises. Each job gets the header row and only whole records.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sobject
|
str
|
The object to load, such as |
required |
operation
|
IngestOperation
|
|
required |
rows
|
Iterable[Mapping[str, Any]] | str | PathLike[str] | bytes
|
The data: an iterable of dicts, the path of a CSV file, or CSV |
required |
columns
|
Sequence[str] | None
|
The columns for dict rows, when rows have different fields. A row may leave a column out, but every field of every row must be a column. Without it, the keys of the first row are the columns. |
None
|
external_id_field
|
str | None
|
The external id field that matches records. Required for
|
None
|
line_ending
|
LineEnding
|
|
'LF'
|
column_delimiter
|
ColumnDelimiter
|
The delimiter of your CSV, or the one the client writes:
|
'COMMA'
|
Returns:
| Type | Description |
|---|---|
AsyncIngestJob
|
The job. Call |
Raises:
| Type | Description |
|---|---|
ValueError
|
invalid arguments, the string |
SalesforceError
|
Salesforce rejected the job or the upload. The client aborts the job it was uploading. Jobs it finished before keep running; the message names them. |
Example
job = await sf.bulk.ingest("Lead", "insert", rows=[{"LastName": "Doe", "Company": "Acme"}])
start_query
async
¶
start_query(
soql: str, *values: Any, include_deleted: bool = False
) -> AsyncQueryJob
Create a Bulk API 2.0 query job and return it without waiting.
Salesforce runs the job in the background. Keep job.id to open the job again later,
also from another process, with :meth:query_job. Salesforce keeps the results for
7 days after the job completes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
soql
|
str
|
The query. |
required |
*values
|
Any
|
Values for the |
()
|
include_deleted
|
bool
|
Use |
False
|
Returns:
| Type | Description |
|---|---|
AsyncQueryJob
|
The job. Call |
Raises:
| Type | Description |
|---|---|
ValueError
|
the query selects |
RequestError
|
Salesforce rejected the job, for example with |
Example
job = await sf.bulk.start_query("SELECT Id, Name FROM Lead") print(job.id) # store it, then open the job again with sf.bulk.query_job(job_id)
query
async
¶
query(
soql: str,
*values: Any,
include_deleted: bool = False,
parallel_downloads: int = 1,
poll: Backoff | None = None,
timeout: float = DEFAULT_TIMEOUT,
) -> AsyncIterator[dict[str, str | None]]
Run a Bulk API 2.0 query job and yield every row.
The client creates the job, polls it until it's complete, and then streams the result
CSV. Rows are dicts with the selected fields as keys ("Owner.Name" for parent
fields). Values are strings, and empty values are None. To keep the job id, wait
in another process or resume a download, use :meth:start_query instead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
soql
|
str
|
The query. |
required |
*values
|
Any
|
Values for the |
()
|
include_deleted
|
bool
|
Use |
False
|
parallel_downloads
|
int
|
With more than 1, the client downloads up to this many result
pages at the same time and still yields rows in order. Salesforce hands out at
most five page URLs at a time ( |
1
|
poll
|
Backoff | None
|
How long to wait between status calls. Defaults to |
None
|
timeout
|
float
|
Seconds to wait for the job to finish. |
DEFAULT_TIMEOUT
|
Raises:
| Type | Description |
|---|---|
ValueError
|
the query selects |
RequestError
|
Salesforce rejected the job, for example with |
BulkJobFailed
|
the job failed or was aborted. |
BulkJobTimeout
|
the job didn't finish in time. |
Example
async for row in sf.bulk.query("SELECT Id, Name FROM Lead", parallel_downloads=4): print(row["Name"])
query_job
async
¶
query_job(job_id: str) -> AsyncQueryJob
Open a query job by its id, for example in a worker after a restart.
The client gets the job's current status. Later calls use the API version that created the job. Salesforce deletes a job 7 days after it finished.
Raises:
| Type | Description |
|---|---|
ValueError
|
|
NotFound
|
Salesforce has no query job with this id: the job was deleted, or the id belongs to an ingest job. |
Example
job = await sf.bulk.query_job(job_id) await job.wait()
ingest_job
async
¶
ingest_job(job_ids: Sequence[str]) -> AsyncIngestJob
Open an ingest job by its ids: the ids of the job that ingest() returned.
An upload over 100 MB runs as several Salesforce jobs. Pass all of their ids, in upload order, to get the same job back. The client gets the status of each one.
Raises:
| Type | Description |
|---|---|
TypeError
|
|
ValueError
|
|
NotFound
|
Salesforce has no ingest job with one of the ids: the job was deleted, or the id belongs to a query job. |
Example
job = await sf.bulk.ingest_job(saved_ids) await job.wait()
expand_compound_fields
async
¶
Replace compound address and geolocation fields with their component fields.
Bulk queries can't select compound fields. This reads the describe of sobject
(from the describe cache when fresh) and swaps each compound field for its parts.
Other names stay as they are.
Example
fields = await sf.bulk.expand_compound_fields("Account", ["Id", "BillingAddress"])
['Id', 'BillingStreet', 'BillingCity', 'BillingState', ...]¶
AsyncIngestJob
¶
AsyncIngestJob(
client: AsyncSalesforce, infos: Sequence[BulkJobInfo]
)
A Bulk API 2.0 ingest job, returned by sf.bulk.ingest().
The upload is complete when you get the job, and Salesforce processes it in the background.
Call :meth:wait, then read the results. If the data was larger than 100 MB, the client
split it over several Salesforce jobs. This object then stands for all of them: ids
lists them, and the results iterate over every job in order.
info
property
¶
info: BulkJobInfo
Status from the latest call: state, record counts and timing.
For several jobs, the counts are summed and the state is the least finished one.
refresh
async
¶
refresh() -> BulkJobInfo
Get the current status of every unfinished job. Returns :attr:info.
wait
async
¶
wait(
*,
poll: Backoff | None = None,
timeout: float = DEFAULT_TIMEOUT,
) -> BulkJobInfo
Poll until every job is finished. Returns the final :attr:info.
A job that ends JobComplete can still have failed records: read
:meth:failed_results or info.records_failed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
poll
|
Backoff | None
|
How long to wait between status calls. Defaults to |
None
|
timeout
|
float
|
Seconds to wait in total. |
DEFAULT_TIMEOUT
|
Raises:
| Type | Description |
|---|---|
BulkJobFailed
|
a job ended |
BulkJobTimeout
|
the jobs didn't finish in time. They keep running; call
|
Example
info = await job.wait(poll=esf.Backoff(start=2, max=30), timeout=3600)
abort
async
¶
abort() -> BulkJobInfo
Abort every job that isn't finished. Salesforce doesn't process aborted jobs.
successful_results
async
¶
successful_results() -> AsyncIterator[dict[str, str]]
Rows Salesforce saved: sf__Id, sf__Created and the columns you uploaded.
The rows are streamed and parsed as they arrive; their order is not the upload order.
failed_results
async
¶
failed_results() -> AsyncIterator[BulkFailure]
Rows Salesforce rejected, with the parsed sf__Error as an :class:ErrorDetail.
Example
async for failure in job.failed_results(): print(failure.error.error_code, failure.fields["Email"])
unprocessed_records
async
¶
unprocessed_records() -> AsyncIterator[dict[str, str]]
Rows Salesforce didn't process because a job failed or was aborted.
AsyncQueryJob
¶
AsyncQueryJob(
client: AsyncSalesforce,
info: BulkJobInfo,
soql: str | None = None,
)
A Bulk API 2.0 query job, returned by sf.bulk.start_query() and sf.bulk.query_job().
The job runs in Salesforce. Call :meth:wait, then read the results with :meth:rows, or
page by page with :meth:pages to resume a download later. id is enough to open the job
again in another process.
refresh
async
¶
refresh() -> BulkJobInfo
Get the current status, if the job isn't finished. Returns :attr:info.
wait
async
¶
wait(
*,
poll: Backoff | None = None,
timeout: float = DEFAULT_TIMEOUT,
) -> BulkJobInfo
Poll until the job is finished. Returns the final :attr:info.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
poll
|
Backoff | None
|
How long to wait between status calls. Defaults to |
None
|
timeout
|
float
|
Seconds to wait in total. |
DEFAULT_TIMEOUT
|
Raises:
| Type | Description |
|---|---|
BulkJobFailed
|
the job ended |
BulkJobTimeout
|
the job didn't finish in time. It keeps running; call |
Example
info = await job.wait(timeout=3600) print(info.records_processed)
rows
async
¶
rows(
*, parallel_downloads: int = 1
) -> AsyncGenerator[dict[str, str | None], None]
Yield every row of a complete job, in order.
Rows are dicts with the selected fields as keys. Values are strings, and empty values
are None. The client reads each page as it arrives, so memory stays flat.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parallel_downloads
|
int
|
With more than 1, the client downloads up to this many result pages at the same time and still yields rows in order. Salesforce hands out at most five page URLs at a time, so values above 5 don't download more. |
1
|
Raises:
| Type | Description |
|---|---|
BulkJobNotComplete
|
the job isn't |
BulkJobFailed
|
the job failed or was aborted. |
Example
await job.wait() async for row in job.rows(parallel_downloads=4): print(row["Id"])
pages
async
¶
pages(
*,
locator: str | None = None,
max_records: int | None = None,
) -> AsyncIterator[AsyncResultPage]
Yield the results of a complete job page by page, so a download can resume.
After you've handled the rows of a page, save page.next_locator. To go on after a
restart, open the job with sf.bulk.query_job(job_id) and pass the saved locator.
A locator stays valid as long as the job exists, and a page can be read again.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
locator
|
str | None
|
The |
None
|
max_records
|
int | None
|
The most rows per page. Salesforce picks the size when it's |
None
|
Raises:
| Type | Description |
|---|---|
BulkJobNotComplete
|
the job isn't |
BulkJobFailed
|
the job failed or was aborted. |
Example
async for page in job.pages(locator=saved, max_records=50_000): async for row in page.rows(): print(row["Id"]) saved = page.next_locator # None after the last page
AsyncResultPage
¶
One page of query results, yielded by :meth:AsyncQueryJob.pages.
The client downloads the whole page to a temporary file before it yields the page, so reading the rows makes no more calls. The file is closed when the iteration moves on to the next page or ends: read the rows before you ask for the next page.
rows
async
¶
rows() -> AsyncIterator[dict[str, str | None]]
The rows of the page, in order, read from the temporary file.
Each call reads the page from the start.
Raises:
| Type | Description |
|---|---|
ValueError
|
the iteration has moved on and the page is closed. |
AsyncUi
¶
AsyncUi(client: AsyncSalesforce)
Read records, metadata and list views the way Lightning shows them (User Interface API).
The UI API applies the user's layouts, field-level security and sharing, and returns values
with their display formatting. Every method is a read, so the client retries it like any
other GET. object_info and picklist_values are served from the describe cache.
record
async
¶
record(
record_id: str,
fields: Sequence[str] | None = None,
layout_types: Sequence[LayoutType] | None = None,
modes: Sequence[Mode] | None = None,
) -> dict[str, Any]
GET ui-api/records/{id}: one record with raw and display values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
record_id
|
str
|
The record id. |
required |
fields
|
Sequence[str] | None
|
Field names qualified with the object, like |
None
|
layout_types
|
Sequence[LayoutType] | None
|
|
None
|
modes
|
Sequence[Mode] | None
|
|
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
The record: |
dict[str, Any]
|
|
dict[str, Any]
|
|
dict[str, Any]
|
currency, the label of a picklist value) and |
Raises:
| Type | Description |
|---|---|
ValueError
|
neither or both of |
NotFound
|
no record with this id, or the user can't see it. |
InvalidField
|
a field in |
object_info
async
¶
GET ui-api/object-info/{name}: object metadata, served from the describe cache.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
sObject API name. |
required |
cached
|
bool
|
|
True
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
|
dict[str, Any]
|
|
Raises:
| Type | Description |
|---|---|
Forbidden
|
the object doesn't exist or the user can't access it (Salesforce answers
403 |
InvalidType
|
the UI API doesn't support the object. |
picklist_values
async
¶
GET ui-api/object-info/{name}/picklist-values/{record_type_id}, served from the describe cache.
Returns the values of every picklist field for one record type, with the values a controlling field allows in a dependent picklist.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
sObject API name. |
required |
record_type_id
|
str
|
The record type. |
required |
cached
|
bool
|
|
True
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
``{"picklistFieldValues": {"LeadSource": {"values": [...], "controllerValues": {...}, |
dict[str, Any]
|
"defaultValue": ...}}}``. |
create_defaults
async
¶
GET ui-api/record-defaults/create/{name}: default values and layout for a new record.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
sObject API name. |
required |
record_type_id
|
str | None
|
The record type of the new record. Salesforce uses the user's default record type when you leave it out. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
|
clone_defaults
async
¶
list_views
async
¶
list_records
async
¶
list_records(
name: str,
list_view: str,
*,
page_size: int | None = None,
page_token: str | None = None,
) -> dict[str, Any]
GET ui-api/list-records/{name}/{list_view}: one page of a list view's records.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
sObject API name. |
required |
list_view
|
str
|
List view API name, like |
required |
page_size
|
int | None
|
Records per page, 1 to 2,000. Salesforce returns 50 when you leave it out. |
None
|
page_token
|
str | None
|
The |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
|
dict[str, Any]
|
last page) and |
AsyncAuthApi
¶
AsyncAuthApi(client: AsyncSalesforce)
sf.auth: code exchange, revoke, userinfo and introspection.
exchange_code
async
¶
exchange_code(
flow: WebServerFlow,
code: str,
*,
code_verifier: str | None = None,
) -> Token
Exchange an authorization code for tokens and save them under flow.token_key.
revoke
async
¶
POST /services/oauth2/revoke and remove the token from memory and the store.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token_key
|
str | None
|
Key of the token to revoke; defaults to this client's (or |
None
|
auth
|
Auth | None
|
The flow that issued the token, when it isn't this client's auth (its domain and client credentials are used for the revoke call). |
None
|
introspect
async
¶
POST /services/oauth2/introspect for the access token under token_key.
auth works as in :meth:revoke.
token
async
¶
token() -> Token
The current token (acquiring one if needed). Treat it as a secret.
Calls through the client never need it. Use it only to hand the access token to other
code, such as a SOAP SessionHeader you build yourself. Never log it.
refresh
async
¶
refresh() -> Token
Refresh this client's token now, even if it looks valid, and return the new token.
Use it when Salesforce rejects a token that the client can't see. An example is a
SOAP SessionHeader sent in a :meth:~AsyncSalesforce.request body: the
INVALID_SESSION_ID fault arrives in the body, so the automatic refresh on
401 doesn't run.
Concurrent calls share one refresh and get the same token. The new token is saved to
the token store, and the client emits sf.auth.refreshed. Treat the token as a secret.
Returns:
| Type | Description |
|---|---|
Token
|
The new token, of the same type as :meth: |
Raises:
| Type | Description |
|---|---|
SessionExpired
|
the client uses |
ReauthorizationRequired
|
the refresh token is expired, revoked or missing. |
RefreshFailed
|
the token endpoint failed or its outcome is unknown. |
OAuthError
|
the token endpoint returned another OAuth error. |
AsyncActions
¶
AsyncActions(client: AsyncSalesforce)
Call invocable actions: standard actions, Flows and Apex @InvocableMethod classes.
Each call takes one input (a dict) or many (a list of dicts):
- one input returns the output values as a
dict. If the invocation fails, the call raises the typed error for its first error entry (for exampleValidationRuleFailed). - a list returns a
BatchResultofActionResult, one per input, in input order. Failed invocations don't raise; callraise_for_errors()to raisePartialFailure. The list is sent in one request. Salesforce runs at most 2,000 inputs per request and fails the rest, so a list of more than 2,000 for an Apex or Flow action raisesValueErrorbefore anything is sent. An uncaught Apex exception fails every input of the request.
A call that runs an action is never resent after it may have reached Salesforce, because the action could run twice.
standard
async
¶
standard(
name: str, inputs: Sequence[Inputs]
) -> BatchResult[ActionResult]
flow
async
¶
flow(
api_name: str, inputs: Sequence[Inputs]
) -> BatchResult[ActionResult]
apex
async
¶
apex(
class_name: str, inputs: Sequence[Inputs]
) -> BatchResult[ActionResult]
list
async
¶
GET actions/standard or GET actions/custom/{kind}: the actions of one kind.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kind
|
str
|
|
required |
Returns:
| Type | Description |
|---|---|
list[dict[str, Any]]
|
One dict per action ( |
AsyncApex
¶
AsyncApex(client: AsyncSalesforce)
Call your own Apex REST classes (@RestResource) under /services/apexrest.
Each method returns what the class returned: decoded JSON, str for a text body,
bytes for a binary body, or None for an empty body. If the call fails, it raises
ApexError with the decoded body in .body. Auth, limit and gateway errors keep their
own classes.
Apex REST runs code, so the client never resends a call after it may have reached
Salesforce, not even a GET. Pass idempotent=True for a method you know is safe to
run twice.
get
async
¶
get(
path: str,
*,
params: Mapping[str, Any] | None = None,
headers: Mapping[str, str] | None = None,
idempotent: bool | None = None,
) -> Any
GET /services/apexrest{path}.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path after |
required |
params
|
Mapping[str, Any] | None
|
Query-string parameters. |
None
|
headers
|
Mapping[str, str] | None
|
Extra request headers. |
None
|
idempotent
|
bool | None
|
|
None
|
post
async
¶
post(
path: str,
json: Any = None,
*,
params: Mapping[str, Any] | None = None,
headers: Mapping[str, str] | None = None,
idempotent: bool | None = None,
) -> Any
POST /services/apexrest{path} with a JSON body.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path after |
required |
json
|
Any
|
Request body, encoded as JSON. |
None
|
params
|
Mapping[str, Any] | None
|
Query-string parameters. |
None
|
headers
|
Mapping[str, str] | None
|
Extra request headers. |
None
|
idempotent
|
bool | None
|
|
None
|
put
async
¶
put(
path: str,
json: Any = None,
*,
params: Mapping[str, Any] | None = None,
headers: Mapping[str, str] | None = None,
idempotent: bool | None = None,
) -> Any
PUT /services/apexrest{path} with a JSON body. Arguments as in :meth:post.
Action
¶
Bases: Generic[R]
Base class for typed invocable action stubs; run one with sf.run(action).
esf generate actions writes subclasses for you. A subclass is a dataclass (or a
Pydantic model) whose fields are the action inputs, with __action__ naming the action
and the type argument naming the result type:
Example
@dataclass(frozen=True, kw_only=True) class AssignLead(esf.Action[AssignLeadResult]): action = ("flow", "Assign_Lead") lead_id: str = field(metadata={"api_name": "leadId"})
result = await sf.run(AssignLead(lead_id="00Q..."))
Attributes:
| Name | Type | Description |
|---|---|---|
__action__ |
tuple[str, str]
|
|
Dataclass fields send their metadata["api_name"] (else the field name). Pydantic models
send their aliases. Fields set to None are not sent.
AsyncLeads
¶
AsyncLeads(client: AsyncSalesforce)
Convert leads into accounts, contacts and opportunities.
Salesforce has no REST resource for this, so the client sends a SOAP convertLead
call with your OAuth access token. You never see the SOAP part.
convert
async
¶
convert(
lead_id: str,
*,
converted_status: str,
account_id: str | None = None,
contact_id: str | None = None,
opportunity_name: str | None = None,
do_not_create_opportunity: bool = False,
owner_id: str | None = None,
send_email: bool = False,
overwrite_lead_source: bool = False,
) -> LeadConvertResult
Convert one lead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lead_id
|
str
|
The lead to convert. |
required |
converted_status
|
str
|
A converted |
required |
account_id
|
str | None
|
Merge into this existing account instead of creating one. |
None
|
contact_id
|
str | None
|
Merge into this existing contact. Needs |
None
|
opportunity_name
|
str | None
|
Name of the new opportunity. |
None
|
do_not_create_opportunity
|
bool
|
Don't create an opportunity. |
False
|
owner_id
|
str | None
|
Owner of the new records. Defaults to the lead owner. |
None
|
send_email
|
bool
|
Email the owner about the new records. |
False
|
overwrite_lead_source
|
bool
|
Overwrite |
False
|
Returns:
| Type | Description |
|---|---|
LeadConvertResult
|
The ids of the converted lead and of the account, contact and opportunity. |
Raises:
| Type | Description |
|---|---|
RecordError
|
Salesforce refused the conversion; the subclass follows the status code. |
ValueError
|
an id is malformed or |
convert_many
async
¶
convert_many(
converts: Iterable[LeadConvert],
) -> BatchResult[LeadConvertResult]
Convert many leads, 100 per SOAP call. Results keep the input order.
Each lead converts on its own: one failure doesn't roll back the others. Check
result.failed or call result.raise_for_errors().
Raises:
| Type | Description |
|---|---|
PartialFailure
|
a whole call of 100 failed while others succeeded. |
SalesforceError
|
every call failed. |
AsyncPlatformEvents
¶
AsyncPlatformEvents(client: AsyncSalesforce)
Publish platform events (Order_Event__e) with the REST API.
A successful publish means Salesforce queued the event. Delivery to subscribers happens
later, so ok doesn't mean a subscriber received it.
publish
async
¶
publish(
name: str, data: Mapping[str, Any]
) -> PublishResult
Publish one event with POST sobjects/{name}.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Event API name, ending in |
required |
data
|
Mapping[str, Any]
|
Field values of the event. |
required |
Returns:
| Type | Description |
|---|---|
PublishResult
|
The queued event, with its |
Raises:
| Type | Description |
|---|---|
EventPublishFailed
|
Salesforce refused the event, for example |
EventPublishUnavailable
|
publishing is down for a moment; try again later. |
RecordError
|
another record error, such as |
publish_many
async
¶
publish_many(
name: str, rows: Iterable[Mapping[str, Any]]
) -> BatchResult[PublishResult]
Publish many events through sObject Collections, 200 per request.
Results keep the input order. Each event publishes on its own: check .failed or
call .raise_for_errors().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Event API name, ending in |
required |
rows
|
Iterable[Mapping[str, Any]]
|
Field values, one mapping per event. |
required |
Raises:
| Type | Description |
|---|---|
PartialFailure
|
a whole request of 200 failed while others succeeded. |
EventPublishFailed
|
every request failed, for example with |
EventPublishUnavailable
|
every request failed because publishing is down for a moment. |
AsyncComposite
¶
AsyncComposite(client: AsyncSalesforce)
Many REST calls in one round trip: Composite, Composite Graph, sObject Tree and Batch.
Every limit is checked before the client sends anything, with a ValueError that names
the limit. A request that writes is never resent after it may have reached Salesforce.
builder
¶
builder(
*,
all_or_none: bool = False,
collate_subrequests: bool = False,
) -> AsyncCompositeBuilder
A Composite request: up to 25 subrequests that can use each other's results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
all_or_none
|
bool
|
Roll back every subrequest if one fails. |
False
|
collate_subrequests
|
bool
|
Let Salesforce group independent subrequests to run them faster. The results still come back in the order you added them. |
False
|
graph
¶
graph() -> AsyncGraphBuilder
A Composite Graph request: graphs of up to 500 subrequests, each graph atomic.
batch
¶
batch(*, halt_on_error: bool = False) -> AsyncBatchBuilder
A Batch request: up to 25 independent subrequests.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
halt_on_error
|
bool
|
Skip the remaining subrequests after the first one fails. |
False
|
tree
async
¶
POST composite/tree/{sobject}: create record trees in one transaction.
Child records go in a child relationship field as {"records": [...]} and need
attributes.type. Give a record attributes.referenceId to find its id in the
result; records without one get ref1, ref2, ... in depth-first order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sobject
|
str
|
sObject type of the root records. |
required |
records
|
Iterable[Mapping[str, Any]]
|
Root records, with their children nested inside. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, str]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
more than 200 records, 5 record types or 5 levels, before anything is sent. |
RecordError
|
Salesforce rejected a record; nothing was saved. The error of the
first rejected record picks the class (for example |
AsyncCompositeBuilder
¶
AsyncCompositeBuilder(
client: AsyncSalesforce,
*,
all_or_none: bool,
collate_subrequests: bool,
)
Bases: CompositeRequest
Builds one Composite request. Get one with sf.composite.builder().
Add up to 25 subrequests with create, update, upsert, delete, get,
query and request. Each returns a :class:~even_simpler_salesforce.Reference;
pass ref.ref("id") to a later subrequest to use the earlier result. Then call
:meth:send.
send
async
¶
send() -> CompositeResult
POST composite: run the subrequests in one round trip.
Returns:
| Type | Description |
|---|---|
CompositeResult
|
One result per subrequest, in the order you added them. A failed subrequest doesn't |
CompositeResult
|
raise; call |
Raises:
| Type | Description |
|---|---|
ValueError
|
no subrequests were added. |
create
¶
update
¶
update(
sobject: str,
record_id: str,
data: Mapping[str, Any],
*,
ref_id: str | None = None,
) -> Reference
PATCH sobjects/{sobject}/{id}: update a record. record_id may be a reference.
upsert
¶
upsert(
sobject: str,
field: str,
value: str,
data: Mapping[str, Any],
*,
ref_id: str | None = None,
) -> Reference
PATCH sobjects/{sobject}/{field}/{value}: upsert a record by external id.
delete
¶
DELETE sobjects/{sobject}/{id}: delete a record. record_id may be a reference.
get
¶
get(
sobject: str,
record_id: str,
fields: Sequence[str] | None = None,
*,
ref_id: str | None = None,
) -> Reference
GET sobjects/{sobject}/{id}: read a record, optionally only some fields.
query
¶
GET query?q=: run a SOQL query (the first page of results).
Positional values fill {} placeholders with the same quoting as sf.query. A
reference passed as a value becomes a quoted literal: WHERE AccountId = {}.
request
¶
Any other REST resource the request type supports, such as sObject Collections.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str
|
|
required |
path
|
str
|
Path relative to |
required |
body
|
Any
|
JSON body (not for |
None
|
ref_id
|
str | None
|
Reference id for this subrequest; generated when omitted. |
None
|
AsyncGraphBuilder
¶
AsyncGraphBuilder(client: AsyncSalesforce)
Bases: GraphRequest
Builds one Composite Graph request. Get one with sf.composite.graph().
Call :meth:graph once per graph and add subrequests to each graph. Each graph runs in
its own transaction: if one of its subrequests fails, Salesforce rolls back that graph
only.
send
async
¶
send() -> list[GraphResult]
POST composite/graph: run every graph in one round trip.
Returns:
| Name | Type | Description |
|---|---|---|
One |
list[GraphResult]
|
class: |
list[GraphResult]
|
them. A failed graph doesn't raise; check |
Raises:
| Type | Description |
|---|---|
ValueError
|
no graphs were added, or a graph has no subrequests. |
AsyncBatchBuilder
¶
AsyncBatchBuilder(
client: AsyncSalesforce, *, halt_on_error: bool
)
Bases: BatchRequest
Builds one Batch request. Get one with sf.composite.batch().
Add up to 25 independent subrequests. Each one runs in its own transaction, and they can't use each other's results.
send
async
¶
send() -> CompositeResult
POST composite/batch: run the subrequests in one round trip.
Returns:
| Type | Description |
|---|---|
CompositeResult
|
One result per subrequest, in the order you added them. Index it by position or by |
CompositeResult
|
the reference id the builder returned. |
Raises:
| Type | Description |
|---|---|
ValueError
|
no subrequests were added. |
create
¶
update
¶
update(
sobject: str,
record_id: str,
data: Mapping[str, Any],
*,
ref_id: str | None = None,
) -> Reference
PATCH sobjects/{sobject}/{id}: update a record. record_id may be a reference.
upsert
¶
upsert(
sobject: str,
field: str,
value: str,
data: Mapping[str, Any],
*,
ref_id: str | None = None,
) -> Reference
PATCH sobjects/{sobject}/{field}/{value}: upsert a record by external id.
delete
¶
DELETE sobjects/{sobject}/{id}: delete a record. record_id may be a reference.
get
¶
get(
sobject: str,
record_id: str,
fields: Sequence[str] | None = None,
*,
ref_id: str | None = None,
) -> Reference
GET sobjects/{sobject}/{id}: read a record, optionally only some fields.
query
¶
GET query?q=: run a SOQL query (the first page of results).
Positional values fill {} placeholders with the same quoting as sf.query. A
reference passed as a value becomes a quoted literal: WHERE AccountId = {}.
request
¶
Any other REST resource the request type supports, such as sObject Collections.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str
|
|
required |
path
|
str
|
Path relative to |
required |
body
|
Any
|
JSON body (not for |
None
|
ref_id
|
str | None
|
Reference id for this subrequest; generated when omitted. |
None
|
Reference
dataclass
¶
Reference(reference_id: str)
A handle on one subrequest. Pass ref(field) to a later subrequest to use its result.
Example
acc = c.create("Account", {"Name": "Acme"}) c.create("Contact", {"LastName": "Doe", "AccountId": acc.ref("id")})
Attributes:
| Name | Type | Description |
|---|---|---|
reference_id |
str
|
The subrequest's |
AsyncPubSub
¶
AsyncPubSub(client: AsyncSalesforce)
Pub/Sub API subscriptions over gRPC. Needs the [pubsub] extra.
Example
async with sf.pubsub.subscribe("/data/AccountChangeEvent") as events: async for ev in events: print(ev.change.change_type, ev.change.record_ids)
To publish platform events, use sf.platform_events.
subscribe
¶
subscribe(
topic: str,
*,
replay: Replay = "latest",
replay_store: AsyncReplayStore | None = None,
on_invalid_replay: OnInvalidReplay = "raise",
batch_size: int = MAX_BATCH_SIZE,
) -> AsyncSubscription
Subscribe to topic. Use the result as a context manager and iterate it.
Delivery is at least once. An event counts as processed when you ask for the next one,
or when the block exits normally. With a replay_store the client saves the position
after each fully consumed batch and on a normal exit, never when the block raises. A
restart therefore redelivers at most one batch. Reconnects resume after the last
processed event, with or without a store.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
topic
|
str
|
|
required |
replay
|
Replay
|
Where to start when the store has no position: |
'latest'
|
replay_store
|
AsyncReplayStore | None
|
Loads the start position and saves progress. Its key is
|
None
|
on_invalid_replay
|
OnInvalidReplay
|
If Salesforce rejects the start position (for example it is older
than 72 hours): |
'raise'
|
batch_size
|
int
|
Most events requested but not yet consumed (1 to 100). |
MAX_BATCH_SIZE
|
Returns:
| Type | Description |
|---|---|
AsyncSubscription
|
An unopened subscription; |
Raises:
| Type | Description |
|---|---|
ValueError
|
a bad argument. |
ImportError
|
the |
AsyncSubscription
¶
AsyncSubscription(
client: AsyncSalesforce,
topic: str,
*,
replay: Replay,
replay_store: AsyncReplayStore | None,
on_invalid_replay: OnInvalidReplay,
batch_size: int,
)
An open subscription: iterate it to receive :class:PubSubEvent objects.
Returned by sf.pubsub.subscribe(); use it as async with ... as events: async for ev in
events. Iterating is the flow control: the client requests more events only after you
have taken the ones it holds. An event counts as processed when you ask for the next one,
or when the block exits normally.
Login flows and tokens¶
Auth
¶
Base class for login flows.
Subclasses are frozen dataclasses. The runtime only uses the members defined here.
base_url
property
¶
base_url: str
Base URL of the OAuth endpoints, resolved from domain (see :func:resolve_domain).
client_id_hash
property
¶
client_id_hash: str
Short SHA-256 prefix of client_id, used in events instead of the id.
token_form
¶
Form for acquiring a new token, given the current one (may be None).
ClientCredentials
dataclass
¶
ClientCredentials(
*,
domain: str,
client_id: str,
client_secret: str,
token_key: str | None = None,
refresh_ahead: timedelta | None = None,
expiry: Expiry = "unknown",
)
Bases: Auth
Client-credentials flow: the app acts as its integration user.
domain must be the org's My Domain URL; login/test aren't supported by
Salesforce for this flow. No refresh token is issued; "refresh" requests a new token.
JwtBearer
dataclass
¶
JwtBearer(
*,
domain: str,
client_id: str,
username: str,
private_key: str | bytes,
private_key_passphrase: str | bytes | None = None,
audience: str | None = None,
token_key: str | None = None,
refresh_ahead: timedelta | None = None,
expiry: Expiry = "unknown",
)
Bases: Auth
JWT bearer flow: server-to-server with a certificate. Needs the [jwt] extra.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
domain
|
str
|
Token endpoint host: |
required |
client_id
|
str
|
Consumer key, sent as the |
required |
username
|
str
|
The user to act as, sent as the |
required |
private_key
|
str | bytes
|
RSA private key in PEM format. |
required |
private_key_passphrase
|
str | bytes | None
|
Passphrase of an encrypted PEM key. The client decrypts the key
locally once, when you create the object; the passphrase is never sent, logged or
shown by |
None
|
audience
|
str | None
|
The |
None
|
token_key
|
str | None
|
Token store key. |
None
|
refresh_ahead
|
timedelta | None
|
Refresh proactively after this |
None
|
expiry
|
Expiry
|
|
'unknown'
|
Raises:
| Type | Description |
|---|---|
ImportError
|
The |
ValueError
|
The key is encrypted and |
token_key
property
¶
token_key: str
token_key if given, else a hash of the domain, client id and username.
aud
property
¶
aud: str
The aud claim. audience wins when set; otherwise it's inferred from domain.
- An Experience Cloud site (a
domainwith a path prefix, or a*.my.site.comhost): the site URL itself. test,https://test.salesforce.comor a*.sandbox.my.salesforce.comhost:https://test.salesforce.com.- Anything else:
https://login.salesforce.com.
Salesforce's JWT bearer flow page names the Experience Cloud site URL (for example
https://site.force.com/customers) as the aud for site users:
https://help.salesforce.com/s/articleView?id=sf.remoteaccess_oauth_jwt_flow.htm&type=5
assertion
¶
A freshly signed RS256 JWT assertion (iss, sub, aud, exp).
WebServerFlow
dataclass
¶
WebServerFlow(
*,
domain: str,
client_id: str,
redirect_uri: str,
client_secret: str | None = None,
scopes: Sequence[str] = ("api", "refresh_token"),
token_key: str,
refresh_ahead: timedelta | None = None,
expiry: Expiry = "unknown",
pkce: bool = True,
)
Bases: Auth
Authorization-code flow with PKCE, for users who log in through the browser.
The app holds the user's refresh token in a :class:TokenStore under token_key, which
is required: one key per Salesforce identity (e.g. f"user:{user_id}").
authorization_url
¶
authorization_url(
state: str | None = None,
*,
scopes: Sequence[str] | None = None,
prompt: str | None = None,
login_hint: str | None = None,
) -> AuthStart
Build the URL to redirect the user to. Pure; no I/O.
code_form
¶
Form for exchanging an authorization code (with the PKCE verifier, if any).
TokenProvider
dataclass
¶
Bases: Auth
A token from your own code, such as the Salesforce CLI or a secrets manager.
The client calls get_token for the first request, and again once when Salesforce
rejects the token with 401. If the new token is rejected too, the call raises
:class:SessionExpired. Concurrent 401 responses share one call.
get_token is a plain function, so one TokenProvider works with both clients.
AsyncSalesforce runs it in a worker thread, so a blocking call such as
subprocess.run doesn't block the event loop. Salesforce calls it directly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
get_token
|
Callable[[], Token]
|
Returns a :class: |
required |
token_key
|
str | None
|
Token store key. Pass one to share the token through a shared token store,
for example across processes. The default is unique to this |
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
|
StaticToken
dataclass
¶
AuthStart
dataclass
¶
Result of :meth:WebServerFlow.authorization_url. Keep state and code_verifier
in the user's session until the callback.
Token
dataclass
¶
Token(
access_token: str,
instance_url: str,
issued_at: datetime,
refresh_token: str | None = None,
id_url: str | None = None,
org_id: str | None = None,
user_id: str | None = None,
scope: frozenset[str] = frozenset(),
signature: str | None = None,
expires_at: datetime | None = None,
version: int = 0,
)
Token stores¶
AsyncTokenStore
¶
Bases: Protocol
Async token store.
Contract for durable stores:
- One record per Salesforce identity, not per app user.
savewithexpected_versionMUST be atomic (compare-and-swap or row lock).- Refresh tokens SHOULD be encrypted at rest.
deleteMUST remove both tokens.
Use esf.testing.token_store_contract to check your implementation.
load
async
¶
Return the stored token (with its version) for key, or None.
save
async
¶
Persist token. If expected_version is not None and the stored version
differs, raise :class:TokenConflict. Returns the stored token with its new version.
delete
async
¶
delete(key: str) -> None
Remove the whole record for key (access and refresh token); no-op if missing.
lock
¶
lock(key: str) -> AbstractAsyncContextManager[None]
Optional cross-process lock. The default is a no-op; in-process single-flight is always applied regardless.
TokenStore
¶
Bases: Protocol
Sync twin of :class:AsyncTokenStore with the same contract.
save
¶
Persist token; compare-and-swap when expected_version is not None.
Returns the stored token with its new version; raises :class:TokenConflict on a
version mismatch.
delete
¶
delete(key: str) -> None
Remove the whole record for key (access and refresh token); no-op if missing.
lock
¶
lock(key: str) -> AbstractContextManager[None]
Optional cross-process lock around refreshes. The default is a no-op.
AsyncInMemoryTokenStore
¶
Dict + version counter + per-key lock. Lost on restart, which is fine for
ClientCredentials and JwtBearer. Use a durable store for WebServerFlow refresh
tokens. The lock is in-process only; share one instance between client families of the same
event loop (async) or process (sync).
The store keeps one record per token_key until :meth:delete; it never drops a record by
itself, because a dropped refresh token means the user must log in again. A new record starts
above the highest version that :meth:delete removed, so a save after a delete never reuses
a version that a stale compare-and-swap could still expect. Idle per-key locks are dropped.
save
async
¶
Store token with the next version; compare-and-swap when expected_version is given.
Raises:
| Type | Description |
|---|---|
TokenConflict
|
|
lock
async
¶
lock(key: str) -> AsyncIterator[None]
Per-key lock, so client families that share this store instance refresh one at a time (a rotated refresh token must never be sent twice).
InMemoryTokenStore
¶
Dict + version counter + per-key lock. Lost on restart, which is fine for
ClientCredentials and JwtBearer. Use a durable store for WebServerFlow refresh
tokens. The lock is in-process only; share one instance between client families of the same
event loop (async) or process (sync).
The store keeps one record per token_key until :meth:delete; it never drops a record by
itself, because a dropped refresh token means the user must log in again. A new record starts
above the highest version that :meth:delete removed, so a save after a delete never reuses
a version that a stale compare-and-swap could still expect. Idle per-key locks are dropped.
save
¶
Store token with the next version; compare-and-swap when expected_version is given.
Raises:
| Type | Description |
|---|---|
TokenConflict
|
|
Replay stores¶
AsyncReplayStore
¶
Bases: Protocol
Where a subscription keeps its position, so a restart resumes where it stopped.
sf.pubsub.subscribe(..., replay_store=store) loads the position before it subscribes
and saves the replay id of the last processed event after each batch and on a normal exit.
The key is "{org_id}:{topic}", so a sandbox refresh or a second org never resumes from
another org's position.
Contract:
loadreturns exactly the bytes that the lastsavefor that key stored.loadof a key that was never saved returnsNone.saveoverwrites; keys are independent of each other.
Use esf.testing.replay_store_contract to check your implementation.
ReplayStore
¶
Bases: Protocol
Where a subscription keeps its position, so a restart resumes where it stopped.
sf.pubsub.subscribe(..., replay_store=store) loads the position before it subscribes
and saves the replay id of the last processed event after each batch and on a normal exit.
The key is "{org_id}:{topic}", so a sandbox refresh or a second org never resumes from
another org's position.
Contract:
loadreturns exactly the bytes that the lastsavefor that key stored.loadof a key that was never saved returnsNone.saveoverwrites; keys are independent of each other.
Use esf.testing.replay_store_contract to check your implementation.
AsyncInMemoryReplayStore
¶
A dict. Lost on restart: use it for tests, or when replaying from replay= after a
restart is fine. Safe to share between subscriptions and threads.
InMemoryReplayStore
¶
Query building¶
soql
¶
Build SOQL with safely quoted values.
{} / {name} placeholders are replaced by quoted literals. Use {{/}} for
literal braces. {:like} escapes % and _ for exact matching inside LIKE.
Example
soql("SELECT Id FROM Lead WHERE Status IN {} AND IsConverted = {}", ["Open"], False) "SELECT Id FROM Lead WHERE Status IN ('Open') AND IsConverted = false"
Field and object names are not placeholders; pass them through :func:soql_identifier.
soql_like
¶
Quote value for use after LIKE, escaping the % and _ wildcards.
pattern adds your own wildcards around the escaped value: soql_like(v, "%{}%")
is a "contains" match.
soql_identifier
¶
soql_identifier(name: str) -> SoqlIdentifier
Validate a field/object name (dotted relationship paths allowed) for use in SOQL.
sosl_term
¶
Quote user input as a SOSL FIND search term, braces included.
Example
sf.search(f"FIND {esf.sosl_term(text)} IN NAME FIELDS RETURNING Account(Id, Name)")
Every SOSL reserved character (? & | ! { } [ ] ( ) ^ ~ * : \ " ' + -) is escaped with
a backslash, so input can't close the braces or add wildcards. Words such as AND, OR
and AND NOT keep their meaning as SOSL operators.
Raises:
| Type | Description |
|---|---|
ValueError
|
|
flatten
¶
Flatten one query row for CSV, DataFrames or JSON (§9.2).
attributesis dropped at every level.- Parent lookups become dotted keys:
{"Owner": {"Name": "Ann"}}→{"Owner.Name": "Ann"}. - A null lookup stays one key:
"Owner": None(read with.get("Owner.Name")). - A child subquery becomes a list of flattened child rows (only the rows present; use
query_iter(..., expand_children=True)to fetch all of them).
It takes one row. For a page or a list of rows, write [esf.flatten(r) for r in page].
Raises:
| Type | Description |
|---|---|
TypeError
|
|
Results¶
QueryResult
dataclass
¶
Bases: Generic[T]
One page of a SOQL query.
Attributes:
| Name | Type | Description |
|---|---|---|
records |
list[T]
|
Rows of this page (plain dicts unless |
total_size |
int
|
|
done |
bool
|
|
cursor |
Cursor | None
|
Opaque cursor for :meth: |
BatchResult
dataclass
¶
Bases: Generic[T]
Ordered results of a multi-record operation (same order as the input).
T is the per-item result type (:class:RecordResult for writes).
RecordResult
dataclass
¶
RecordResult(
ok: bool,
id: str | None = None,
created: bool | None = None,
errors: tuple[ErrorDetail, ...] = (),
)
Outcome for one record of a multi-record operation.
ActionResult
dataclass
¶
ActionResult(
ok: bool,
outputs: Mapping[str, Any] = (lambda: {})(),
errors: tuple[ErrorDetail, ...] = (),
action_name: str | None = None,
)
Outcome of one invocation of an invocable action (one entry per input).
Attributes:
| Name | Type | Description |
|---|---|---|
ok |
bool
|
|
outputs |
Mapping[str, Any]
|
|
errors |
tuple[ErrorDetail, ...]
|
The error entries when it failed. |
action_name |
str | None
|
|
UpsertResult
dataclass
¶
Result of an upsert by external id.
LeadConvert
dataclass
¶
LeadConvert(
lead_id: str,
converted_status: str,
account_id: str | None = None,
contact_id: str | None = None,
opportunity_name: str | None = None,
do_not_create_opportunity: bool = False,
owner_id: str | None = None,
send_email: bool = False,
overwrite_lead_source: bool = False,
)
One lead to convert with sf.leads.convert_many() (Partner LeadConvert).
Attributes:
| Name | Type | Description |
|---|---|---|
lead_id |
str
|
The lead to convert. |
converted_status |
str
|
A converted |
account_id |
str | None
|
Merge into this existing account instead of creating one. |
contact_id |
str | None
|
Merge into this existing contact (needs |
opportunity_name |
str | None
|
Name of the new opportunity (default: the company name). |
do_not_create_opportunity |
bool
|
Don't create an opportunity. |
owner_id |
str | None
|
Owner of the new records (default: the lead owner). |
send_email |
bool
|
Email the new owner ( |
overwrite_lead_source |
bool
|
Overwrite |
Raises:
| Type | Description |
|---|---|
ValueError
|
an id is not a 15- or 18-character Salesforce id, |
TypeError
|
a text value is not a |
LeadConvertResult
dataclass
¶
LeadConvertResult(
ok: bool,
lead_id: str | None = None,
account_id: str | None = None,
contact_id: str | None = None,
opportunity_id: str | None = None,
errors: tuple[ErrorDetail, ...] = (),
)
Outcome of one lead conversion (Partner LeadConvertResult).
Attributes:
| Name | Type | Description |
|---|---|---|
ok |
bool
|
Whether the lead was converted. |
lead_id |
str | None
|
The converted lead. |
account_id |
str | None
|
The new account, or the one you passed. |
contact_id |
str | None
|
The new contact, or the one you passed. |
opportunity_id |
str | None
|
The new opportunity, or |
errors |
tuple[ErrorDetail, ...]
|
Why the conversion failed. |
MergeResult
dataclass
¶
MergeResult(
ok: bool,
id: str | None = None,
merged_ids: tuple[str, ...] = (),
updated_related_ids: tuple[str, ...] = (),
errors: tuple[ErrorDetail, ...] = (),
)
Outcome of sf.merge() (Partner MergeResult).
Attributes:
| Name | Type | Description |
|---|---|---|
ok |
bool
|
Whether the records were merged. |
id |
str | None
|
The master record. |
merged_ids |
tuple[str, ...]
|
The records merged into the master and deleted. |
updated_related_ids |
tuple[str, ...]
|
Related records that now point to the master. |
errors |
tuple[ErrorDetail, ...]
|
Why the merge failed. |
PublishResult
dataclass
¶
PublishResult(
ok: bool,
id: str | None = None,
uuid: str | None = None,
errors: tuple[ErrorDetail, ...] = (),
)
Outcome of publishing one platform event.
ok means Salesforce queued the event; delivery happens later. Use uuid to match the
event to its EventUuid on the subscriber side.
Attributes:
| Name | Type | Description |
|---|---|---|
ok |
bool
|
Whether Salesforce queued the event. |
id |
str | None
|
The id Salesforce returned for the publish call. |
uuid |
str | None
|
The event's |
errors |
tuple[ErrorDetail, ...]
|
Why the publish failed. |
PubSubEvent
dataclass
¶
PubSubEvent(
topic: str,
replay_id: bytes,
event_id: str | None,
schema_id: str,
payload: Mapping[str, Any],
change: ChangeHeader | None = None,
)
One event received from a Pub/Sub API subscription.
Attributes:
| Name | Type | Description |
|---|---|---|
topic |
str
|
The topic you subscribed to, e.g. |
replay_id |
bytes
|
Opaque position of the event in the stream. Store it to resume after it. Replay ids are not unique across org migrations: never de-duplicate on them. |
event_id |
str | None
|
|
schema_id |
str
|
Id of the Avro schema the payload was written with. |
payload |
Mapping[str, Any]
|
The decoded event. Change events keep their |
change |
ChangeHeader | None
|
The decoded header of a change event, |
ChangeHeader
dataclass
¶
ChangeHeader(
entity_name: str,
change_type: ChangeType,
record_ids: tuple[str, ...] = (),
changed_fields: tuple[str, ...] = (),
nulled_fields: tuple[str, ...] = (),
diff_fields: tuple[str, ...] = (),
transaction_key: str | None = None,
sequence_number: int | None = None,
commit_timestamp: datetime | None = None,
commit_user: str | None = None,
commit_number: int | None = None,
change_origin: str | None = None,
)
The decoded ChangeEventHeader of a Change Data Capture event.
The *_fields tuples hold field names, decoded from the bitmaps Salesforce sends. A
component of a compound field is named Parent.Child, for example
BillingAddress.City.
Attributes:
| Name | Type | Description |
|---|---|---|
entity_name |
str
|
The sObject, e.g. |
change_type |
ChangeType
|
What happened to the records. |
record_ids |
tuple[str, ...]
|
The changed records. Several ids mean Salesforce merged identical changes into one event. Empty for an overflow event. |
changed_fields |
tuple[str, ...]
|
Fields set by an update ( |
nulled_fields |
tuple[str, ...]
|
Fields set to |
diff_fields |
tuple[str, ...]
|
Long text fields sent as a diff instead of the full value. |
transaction_key |
str | None
|
Groups the events of one transaction. |
sequence_number |
int | None
|
Order of this event within its transaction (starts at 1). |
commit_timestamp |
datetime | None
|
When the transaction was committed (UTC). |
commit_user |
str | None
|
Id of the user who made the change. |
commit_number |
int | None
|
The system change number of the commit. |
change_origin |
str | None
|
The client that made the change, e.g. |
ChangeType
¶
ChangeEventHeader.changeType of a Change Data Capture event.
GAP_* events say that Salesforce could not produce a normal change event, so they carry
no field values: re-read the records. GAP_OVERFLOW says that one transaction changed
too many records for Salesforce to send a change event for each one: re-sync the object.
SNAPSHOT is in the ChangeType enum of the change event schema that Salesforce sends
(org-observed, API v68.0), but the Change Data Capture documentation doesn't say when an
event has it. It is listed so that such an event doesn't end the subscription.
FileLink
dataclass
¶
FileLink(
link_id: str,
content_document_id: str,
latest_version_id: str | None,
title: str | None,
file_extension: str | None,
size: int | None,
share_type: str | None,
visibility: str | None,
)
A file linked to a record: one ContentDocumentLink row, from sf.files.list_for().
Attributes:
| Name | Type | Description |
|---|---|---|
link_id |
str
|
Id of the |
content_document_id |
str
|
Id of the |
latest_version_id |
str | None
|
Id of the latest published |
title |
str | None
|
Title of the file. |
file_extension |
str | None
|
File extension without the dot, for example |
size |
int | None
|
Size of the latest version in bytes. |
share_type |
str | None
|
|
visibility |
str | None
|
|
CompositeResult
dataclass
¶
CompositeResult(
results: list[SubrequestResult],
operation: str | None = None,
)
Results of a Composite or Batch request, one per subrequest, in the order you added them.
Index it by position or by reference id: result[0], result["acc"]. A failed
subrequest doesn't raise; call :meth:raise_for_errors.
Attributes:
| Name | Type | Description |
|---|---|---|
results |
list[SubrequestResult]
|
One :class: |
operation |
str | None
|
|
failed
property
¶
failed: list[SubrequestResult]
Subrequests that failed, including the ones Salesforce halted or rolled back.
raise_for_errors
¶
Raise the typed error of the first subrequest that caused a failure.
Subrequests that Salesforce only halted or rolled back (PROCESSING_HALTED) don't
pick the class: the real cause does, for example :class:ValidationRuleFailed. The
exception's .errors holds the error entries of every failed subrequest.
SubrequestResult
dataclass
¶
SubrequestResult(
reference_id: str | None,
status: int,
body: Any = None,
headers: Mapping[str, str] = (lambda: {})(),
error: SalesforceError | None = None,
)
Outcome of one subrequest of a Composite, Composite Graph or Batch request.
Attributes:
| Name | Type | Description |
|---|---|---|
reference_id |
str | None
|
The subrequest's reference id (the client's name for it in a Batch). |
status |
int
|
HTTP status of the subrequest ( |
body |
Any
|
Decoded body of the subrequest: the record for a get, the query page for a
query, |
headers |
Mapping[str, str]
|
Response headers of the subrequest, such as |
error |
SalesforceError | None
|
The typed error for a failed subrequest (§8), else |
GraphResult
dataclass
¶
GraphResult(
graph_id: str, ok: bool, results: CompositeResult
)
Outcome of one graph of a Composite Graph request.
A graph is atomic: if one subrequest fails, Salesforce rolls back the whole graph, and only that graph.
Attributes:
| Name | Type | Description |
|---|---|---|
graph_id |
str
|
The graph's id. |
ok |
bool
|
|
results |
CompositeResult
|
The graph's subrequest results. |
raise_for_errors
¶
Raise the typed error of the subrequest that made this graph fail.
BulkJobState
¶
State of a Bulk API 2.0 job (Job States, Bulk API 2.0 Developer Guide).
JobComplete, Failed and Aborted are final: the job doesn't change after them.
The values equal the strings Salesforce sends, so state == "JobComplete" also works.
BulkJobInfo
dataclass
¶
BulkJobInfo(
id: str,
operation: str | None,
sobject: str | None,
state: BulkJobState,
api_version: str,
records_processed: int = 0,
records_failed: int = 0,
created_date: datetime | None = None,
system_modstamp: datetime | None = None,
total_processing_ms: int | None = None,
error_message: str | None = None,
raw: Mapping[str, Any] = (lambda: {})(),
)
Status of a Bulk API 2.0 job, from the latest status call.
Attributes:
| Name | Type | Description |
|---|---|---|
id |
str
|
Job id ( |
operation |
str | None
|
|
sobject |
str | None
|
The object of the job. |
state |
BulkJobState
|
The job state. |
api_version |
str
|
The API version that created the job. Results are read with it. |
records_processed |
int
|
|
records_failed |
int
|
|
created_date |
datetime | None
|
When the job was created. |
system_modstamp |
datetime | None
|
When Salesforce last changed the job. |
total_processing_ms |
int | None
|
|
error_message |
str | None
|
|
raw |
Mapping[str, Any]
|
The job info as Salesforce sent it. Empty for an ingest split over several jobs. |
BulkFailure
dataclass
¶
BulkFailure(
error: ErrorDetail,
id: str | None = None,
fields: Mapping[str, str] = (lambda: {})(),
)
One row of the failed-results CSV of a Bulk ingest job.
Attributes:
| Name | Type | Description |
|---|---|---|
error |
ErrorDetail
|
The parsed |
id |
str | None
|
|
fields |
Mapping[str, str]
|
The other columns, as you uploaded them. |
QueryPlan
dataclass
¶
QueryPlan(
leading_operation: str,
relative_cost: float,
cardinality: int,
sobject_cardinality: int,
sobject_type: str,
fields: tuple[str, ...] = (),
notes: tuple[QueryPlanNote, ...] = (),
)
One plan from GET query?explain= (Salesforce Beta feature). Plans come sorted from
most to least optimal; the first is the one Salesforce would use.
Attributes:
| Name | Type | Description |
|---|---|---|
leading_operation |
str
|
|
relative_cost |
float
|
Cost against the selectivity threshold; above 1.0 is not selective. |
cardinality |
int
|
Estimated rows the plan returns. |
sobject_cardinality |
int
|
Approximate number of records of the queried object in the org. |
sobject_type |
str
|
The queried object. |
fields |
tuple[str, ...]
|
Indexed fields the plan uses. |
notes |
tuple[QueryPlanNote, ...]
|
Why other fields couldn't use an index. |
QueryPlanNote
dataclass
¶
QueryPlanNote(
description: str,
fields: tuple[str, ...] = (),
table_enum_or_id: str | None = None,
)
A note on why a query plan can't use an index (notes[] of query?explain=).
Limit
dataclass
¶
UsageSnapshot
dataclass
¶
UsageSnapshot(
api_used: int | None,
api_max: int | None,
api_fraction: float | None,
as_of: datetime | None,
calls_by_operation: Mapping[str, int],
calls_by_sobject: Mapping[str, int],
calls_by_caller: Mapping[str, int],
errors_by_code: Mapping[str, int],
retries: int,
refreshes: int,
projected_exhaustion: datetime | None,
api_bursts_used: int | None = None,
api_bursts_max: int | None = None,
)
Point-in-time view of API usage (§10.3).
api_* values come from the latest Sforce-Limit-Info header (org-wide). Counters are
per process.
Configuration¶
Timeouts
dataclass
¶
HTTP timeouts in seconds (§7.2).
RetryPolicy
dataclass
¶
RetryPolicy(
max_attempts: int = 3,
base_delay: float = 0.25,
max_delay: float = 8.0,
jitter: bool = True,
respect_retry_after: bool = True,
max_retry_after: float = 30.0,
)
Retry policy (§7.4).
Attributes:
| Name | Type | Description |
|---|---|---|
max_attempts |
int
|
Total attempts per logical call, including the first one. |
base_delay |
float
|
First backoff delay in seconds (doubled per attempt). |
max_delay |
float
|
Cap for the exponential backoff. |
jitter |
bool
|
Use full jitter ( |
respect_retry_after |
bool
|
Honour a |
max_retry_after |
float
|
A |
Budget
dataclass
¶
Budget(
warn_at: tuple[float, ...] = (0.5, 0.8, 0.95),
pause_low_priority_above: float | None = 0.8,
block_all_above: float | None = None,
)
API usage budget (§10.4).
Attributes:
| Name | Type | Description |
|---|---|---|
warn_at |
tuple[float, ...]
|
Fractions of the daily API limit at which |
pause_low_priority_above |
float | None
|
Raise :class: |
block_all_above |
float | None
|
Raise :class: |
DescribeCacheConfig
dataclass
¶
DescribeCacheConfig(
ttl: float = 3600.0,
max_entries: int = 500,
revalidate: bool = True,
stale_ttl: float = 86400.0,
)
Describe cache settings (§12).
Attributes:
| Name | Type | Description |
|---|---|---|
ttl |
float
|
Seconds a cached describe is used without asking Salesforce. |
max_entries |
int
|
Maximum entries in the default in-memory cache. |
revalidate |
bool
|
When an entry is stale, revalidate with |
stale_ttl |
float
|
Seconds a stale entry is kept for revalidation. |
DuplicateRules
dataclass
¶
DuplicateRules(
allow_save: bool = False,
include_record_details: bool = False,
run_as_current_user: bool = False,
)
How a write handles the org's duplicate rules: Sforce-Duplicate-Rule-Header.
Pass it as duplicate_rules= to create, update and upsert (single records and
sObject Collections). All three flags are always sent. The defaults equal Salesforce's, so
DuplicateRules() behaves like sending no header. Needs API 52.0 or later.
See the REST API Developer Guide, Duplicate Rule Header: https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/headers_duplicaterules.htm
Attributes:
| Name | Type | Description |
|---|---|---|
allow_save |
bool
|
Save the record even when a duplicate rule alerts. A rule that blocks still blocks. |
include_record_details |
bool
|
In a |
run_as_current_user |
bool
|
Find duplicates with the sharing rules of the running user, not with system access. |
Backoff
dataclass
¶
How often to poll a long-running job, such as a Bulk job in job.wait().
The first wait is start seconds. Each next wait is factor times longer, up to
max seconds. There is no jitter: a status call is cheap and the job runs in Salesforce.
Attributes:
| Name | Type | Description |
|---|---|---|
start |
float
|
First delay in seconds. |
max |
float
|
Longest delay in seconds. |
factor |
float
|
Growth of the delay per poll. |
Cache
¶
Bases: Protocol
Shared cache used for describe results.
Implement this to share describes across processes (e.g. Redis). Values are plain JSON-compatible data. Implementations must be thread-safe and should be fast: the async client calls them inline.
MemoryCache
¶
Thread-safe in-memory cache with per-entry TTL and LRU eviction.
set
¶
Store value for ttl seconds; evicts the least recently used entry when full.
call_context
¶
call_context(
*,
caller: str | None = None,
priority: Priority | None = None,
) -> Iterator[CallContext]
Tag every Salesforce call made inside the block (works across awaits).
Example
with esf.call_context(caller="route:/leads", priority="high"): await sf.query(...)
Observability¶
Event
dataclass
¶
Observer
¶
capture
¶
Collect a roll-up of every Salesforce call made inside the block.
Contextvar-scoped: works across awaits and child clients. Nested blocks each get the calls.
Summary
¶
StdlibLogging
¶
Structlog
¶
OpenTelemetry
¶
OpenTelemetry(
tracer_provider: Any = None,
meter_provider: Any = None,
*,
metric_attributes: Iterable[
str
] = DEFAULT_METRIC_ATTRIBUTES,
)
A span per sf.request plus metrics.
Metrics: counters esf.requests and esf.errors, histogram esf.duration (ms),
gauge esf.api_usage (fraction of the daily limit). For Pub/Sub subscriptions, counter
esf.pubsub.events and histogram esf.pubsub.lag (ms between an event's commit or
creation time and its arrival), both labelled with topic.
Spans carry every attribute. Metrics carry only metric_attributes
(:data:DEFAULT_METRIC_ATTRIBUTES), leaving out caller and sobject, which can take
many distinct values. Pass e.g. (*DEFAULT_METRIC_ATTRIBUTES, "sobject") to add them.
DebugPrinter
¶
Errors¶
Exception hierarchy.
Every error raised by the library is a :class:SalesforceError. All errors share one shape,
regardless of which Salesforce API produced them (REST, OAuth, Collections, SOAP, ...).
This module performs no I/O.
ErrorDetail
dataclass
¶
ErrorDetail(
error_code: str | None,
message: str,
fields: tuple[str, ...] = (),
extended: Mapping[str, Any] = (lambda: {})(),
)
One entry of a (possibly multi-error) Salesforce error body.
Hashable: extended takes part in == but not in hash(), because it is a dict.
SalesforceError
¶
SalesforceError(
message: str = "",
*,
error_code: str | None = None,
fields: tuple[str, ...] | list[str] = (),
status: int | None = None,
operation: str | None = None,
sobject: str | None = None,
method: str | None = None,
path: str | None = None,
request_id: str | None = None,
retryable: bool | None = None,
errors: tuple[ErrorDetail, ...]
| list[ErrorDetail] = (),
raw: bytes | str | None = None,
tag: str | None = None,
hint: str | None = None,
docs_url: str | None = None,
)
Bases: Exception
Base class for every error raised by the library.
Attributes:
| Name | Type | Description |
|---|---|---|
message |
str
|
Human-readable message, from Salesforce when available. |
error_code |
str | None
|
Salesforce |
fields |
tuple[str, ...]
|
Fields Salesforce reported as affected. |
status |
int | None
|
HTTP status, if there was a response. |
operation |
str | None
|
Library operation name, e.g. |
sobject |
str | None
|
sObject type involved, if any. |
method |
str | None
|
HTTP method. |
path |
str | None
|
Request path with ids replaced by |
request_id |
str | None
|
Salesforce request id header, if present. |
retryable |
bool
|
Whether the error is transient in principle. |
errors |
tuple[ErrorDetail, ...]
|
Every error entry when Salesforce returned several. |
raw |
bytes | str | None
|
Original response body, for debugging (never logged by the library). |
tag |
str | None
|
Custom error tag parsed from the message ( |
hint |
str | None
|
A likely fix, computed from data the client already had (never an API call).
|
docs_url |
str | None
|
Troubleshooting entry for this error class on the docs site. |
TransportError
¶
TransportError(
message: str = "",
*,
error_code: str | None = None,
fields: tuple[str, ...] | list[str] = (),
status: int | None = None,
operation: str | None = None,
sobject: str | None = None,
method: str | None = None,
path: str | None = None,
request_id: str | None = None,
retryable: bool | None = None,
errors: tuple[ErrorDetail, ...]
| list[ErrorDetail] = (),
raw: bytes | str | None = None,
tag: str | None = None,
hint: str | None = None,
docs_url: str | None = None,
)
ConnectError
¶
ConnectError(
message: str = "",
*,
error_code: str | None = None,
fields: tuple[str, ...] | list[str] = (),
status: int | None = None,
operation: str | None = None,
sobject: str | None = None,
method: str | None = None,
path: str | None = None,
request_id: str | None = None,
retryable: bool | None = None,
errors: tuple[ErrorDetail, ...]
| list[ErrorDetail] = (),
raw: bytes | str | None = None,
tag: str | None = None,
hint: str | None = None,
docs_url: str | None = None,
)
RequestTimeout
¶
RequestTimeout(
message: str = "",
*,
error_code: str | None = None,
fields: tuple[str, ...] | list[str] = (),
status: int | None = None,
operation: str | None = None,
sobject: str | None = None,
method: str | None = None,
path: str | None = None,
request_id: str | None = None,
retryable: bool | None = None,
errors: tuple[ErrorDetail, ...]
| list[ErrorDetail] = (),
raw: bytes | str | None = None,
tag: str | None = None,
hint: str | None = None,
docs_url: str | None = None,
)
AuthError
¶
AuthError(
message: str = "",
*,
error_code: str | None = None,
fields: tuple[str, ...] | list[str] = (),
status: int | None = None,
operation: str | None = None,
sobject: str | None = None,
method: str | None = None,
path: str | None = None,
request_id: str | None = None,
retryable: bool | None = None,
errors: tuple[ErrorDetail, ...]
| list[ErrorDetail] = (),
raw: bytes | str | None = None,
tag: str | None = None,
hint: str | None = None,
docs_url: str | None = None,
)
SessionExpired
¶
SessionExpired(
message: str = "",
*,
error_code: str | None = None,
fields: tuple[str, ...] | list[str] = (),
status: int | None = None,
operation: str | None = None,
sobject: str | None = None,
method: str | None = None,
path: str | None = None,
request_id: str | None = None,
retryable: bool | None = None,
errors: tuple[ErrorDetail, ...]
| list[ErrorDetail] = (),
raw: bytes | str | None = None,
tag: str | None = None,
hint: str | None = None,
docs_url: str | None = None,
)
ReauthorizationRequired
¶
ReauthorizationRequired(
message: str = "",
*,
error_code: str | None = None,
fields: tuple[str, ...] | list[str] = (),
status: int | None = None,
operation: str | None = None,
sobject: str | None = None,
method: str | None = None,
path: str | None = None,
request_id: str | None = None,
retryable: bool | None = None,
errors: tuple[ErrorDetail, ...]
| list[ErrorDetail] = (),
raw: bytes | str | None = None,
tag: str | None = None,
hint: str | None = None,
docs_url: str | None = None,
)
RefreshFailed
¶
TokenConflict
¶
TokenConflict(
message: str = "",
*,
error_code: str | None = None,
fields: tuple[str, ...] | list[str] = (),
status: int | None = None,
operation: str | None = None,
sobject: str | None = None,
method: str | None = None,
path: str | None = None,
request_id: str | None = None,
retryable: bool | None = None,
errors: tuple[ErrorDetail, ...]
| list[ErrorDetail] = (),
raw: bytes | str | None = None,
tag: str | None = None,
hint: str | None = None,
docs_url: str | None = None,
)
TokenIdentityChanged
¶
TokenIdentityChanged(
message: str = "",
*,
error_code: str | None = None,
fields: tuple[str, ...] | list[str] = (),
status: int | None = None,
operation: str | None = None,
sobject: str | None = None,
method: str | None = None,
path: str | None = None,
request_id: str | None = None,
retryable: bool | None = None,
errors: tuple[ErrorDetail, ...]
| list[ErrorDetail] = (),
raw: bytes | str | None = None,
tag: str | None = None,
hint: str | None = None,
docs_url: str | None = None,
)
Bases: AuthError
A new or re-read token belongs to another org or user than the token it replaces.
The client refuses to use it, so it never acts as another user. The message names what changed (org or user) and never contains a token.
OAuthError
¶
RequestError
¶
RequestError(
message: str = "",
*,
error_code: str | None = None,
fields: tuple[str, ...] | list[str] = (),
status: int | None = None,
operation: str | None = None,
sobject: str | None = None,
method: str | None = None,
path: str | None = None,
request_id: str | None = None,
retryable: bool | None = None,
errors: tuple[ErrorDetail, ...]
| list[ErrorDetail] = (),
raw: bytes | str | None = None,
tag: str | None = None,
hint: str | None = None,
docs_url: str | None = None,
)
MalformedQuery
¶
MalformedQuery(
message: str = "",
*,
error_code: str | None = None,
fields: tuple[str, ...] | list[str] = (),
status: int | None = None,
operation: str | None = None,
sobject: str | None = None,
method: str | None = None,
path: str | None = None,
request_id: str | None = None,
retryable: bool | None = None,
errors: tuple[ErrorDetail, ...]
| list[ErrorDetail] = (),
raw: bytes | str | None = None,
tag: str | None = None,
hint: str | None = None,
docs_url: str | None = None,
)
InvalidField
¶
InvalidField(
message: str = "",
*,
error_code: str | None = None,
fields: tuple[str, ...] | list[str] = (),
status: int | None = None,
operation: str | None = None,
sobject: str | None = None,
method: str | None = None,
path: str | None = None,
request_id: str | None = None,
retryable: bool | None = None,
errors: tuple[ErrorDetail, ...]
| list[ErrorDetail] = (),
raw: bytes | str | None = None,
tag: str | None = None,
hint: str | None = None,
docs_url: str | None = None,
)
InvalidType
¶
InvalidType(
message: str = "",
*,
error_code: str | None = None,
fields: tuple[str, ...] | list[str] = (),
status: int | None = None,
operation: str | None = None,
sobject: str | None = None,
method: str | None = None,
path: str | None = None,
request_id: str | None = None,
retryable: bool | None = None,
errors: tuple[ErrorDetail, ...]
| list[ErrorDetail] = (),
raw: bytes | str | None = None,
tag: str | None = None,
hint: str | None = None,
docs_url: str | None = None,
)
NotFound
¶
NotFound(
message: str = "",
*,
error_code: str | None = None,
fields: tuple[str, ...] | list[str] = (),
status: int | None = None,
operation: str | None = None,
sobject: str | None = None,
method: str | None = None,
path: str | None = None,
request_id: str | None = None,
retryable: bool | None = None,
errors: tuple[ErrorDetail, ...]
| list[ErrorDetail] = (),
raw: bytes | str | None = None,
tag: str | None = None,
hint: str | None = None,
docs_url: str | None = None,
)
Forbidden
¶
Forbidden(
message: str = "",
*,
error_code: str | None = None,
fields: tuple[str, ...] | list[str] = (),
status: int | None = None,
operation: str | None = None,
sobject: str | None = None,
method: str | None = None,
path: str | None = None,
request_id: str | None = None,
retryable: bool | None = None,
errors: tuple[ErrorDetail, ...]
| list[ErrorDetail] = (),
raw: bytes | str | None = None,
tag: str | None = None,
hint: str | None = None,
docs_url: str | None = None,
)
MultipleMatches
¶
Conflict
¶
Conflict(
message: str = "",
*,
error_code: str | None = None,
fields: tuple[str, ...] | list[str] = (),
status: int | None = None,
operation: str | None = None,
sobject: str | None = None,
method: str | None = None,
path: str | None = None,
request_id: str | None = None,
retryable: bool | None = None,
errors: tuple[ErrorDetail, ...]
| list[ErrorDetail] = (),
raw: bytes | str | None = None,
tag: str | None = None,
hint: str | None = None,
docs_url: str | None = None,
)
Gone
¶
Gone(
message: str = "",
*,
error_code: str | None = None,
fields: tuple[str, ...] | list[str] = (),
status: int | None = None,
operation: str | None = None,
sobject: str | None = None,
method: str | None = None,
path: str | None = None,
request_id: str | None = None,
retryable: bool | None = None,
errors: tuple[ErrorDetail, ...]
| list[ErrorDetail] = (),
raw: bytes | str | None = None,
tag: str | None = None,
hint: str | None = None,
docs_url: str | None = None,
)
RequestTooLarge
¶
RequestTooLarge(
message: str = "",
*,
error_code: str | None = None,
fields: tuple[str, ...] | list[str] = (),
status: int | None = None,
operation: str | None = None,
sobject: str | None = None,
method: str | None = None,
path: str | None = None,
request_id: str | None = None,
retryable: bool | None = None,
errors: tuple[ErrorDetail, ...]
| list[ErrorDetail] = (),
raw: bytes | str | None = None,
tag: str | None = None,
hint: str | None = None,
docs_url: str | None = None,
)
UnsupportedApiVersion
¶
UnsupportedApiVersion(
message: str = "",
*,
error_code: str | None = None,
fields: tuple[str, ...] | list[str] = (),
status: int | None = None,
operation: str | None = None,
sobject: str | None = None,
method: str | None = None,
path: str | None = None,
request_id: str | None = None,
retryable: bool | None = None,
errors: tuple[ErrorDetail, ...]
| list[ErrorDetail] = (),
raw: bytes | str | None = None,
tag: str | None = None,
hint: str | None = None,
docs_url: str | None = None,
)
Bases: RequestError
The API version doesn't fit the call. Two sources, told apart by error_code:
"UNSUPPORTED_API_VERSION": Salesforce rejected the configuredapi_version. A version newer than the org's release is not reported this way: Salesforce answers 404NOT_FOUND(:class:NotFound) on every resource (observed on a v68.0 org)."API_VERSION_TOO_OLD": raised by the library before sending, because a feature needs a newerapi_versionthan configured.
RecordError
¶
RecordError(
message: str = "",
*,
error_code: str | None = None,
fields: tuple[str, ...] | list[str] = (),
status: int | None = None,
operation: str | None = None,
sobject: str | None = None,
method: str | None = None,
path: str | None = None,
request_id: str | None = None,
retryable: bool | None = None,
errors: tuple[ErrorDetail, ...]
| list[ErrorDetail] = (),
raw: bytes | str | None = None,
tag: str | None = None,
hint: str | None = None,
docs_url: str | None = None,
)
ValidationRuleFailed
¶
ValidationRuleFailed(
message: str = "",
*,
error_code: str | None = None,
fields: tuple[str, ...] | list[str] = (),
status: int | None = None,
operation: str | None = None,
sobject: str | None = None,
method: str | None = None,
path: str | None = None,
request_id: str | None = None,
retryable: bool | None = None,
errors: tuple[ErrorDetail, ...]
| list[ErrorDetail] = (),
raw: bytes | str | None = None,
tag: str | None = None,
hint: str | None = None,
docs_url: str | None = None,
)
Bases: RecordError
FIELD_CUSTOM_VALIDATION_EXCEPTION: validation rules, Flow custom errors, addError().
RequiredFieldMissing
¶
RequiredFieldMissing(
message: str = "",
*,
error_code: str | None = None,
fields: tuple[str, ...] | list[str] = (),
status: int | None = None,
operation: str | None = None,
sobject: str | None = None,
method: str | None = None,
path: str | None = None,
request_id: str | None = None,
retryable: bool | None = None,
errors: tuple[ErrorDetail, ...]
| list[ErrorDetail] = (),
raw: bytes | str | None = None,
tag: str | None = None,
hint: str | None = None,
docs_url: str | None = None,
)
DuplicateDetected
¶
Bases: RecordError
DUPLICATES_DETECTED: a duplicate rule blocked the record, or alerted without allow_save.
.duplicates is Salesforce's duplicateResult as a dict (duplicateRule,
matchResults[].matchRecords[].record, ...), or None when the response has none
(sObject Collections). Each record holds only Id unless the write sent
duplicate_rules=DuplicateRules(include_record_details=True).
InvalidReference
¶
InvalidReference(
message: str = "",
*,
error_code: str | None = None,
fields: tuple[str, ...] | list[str] = (),
status: int | None = None,
operation: str | None = None,
sobject: str | None = None,
method: str | None = None,
path: str | None = None,
request_id: str | None = None,
retryable: bool | None = None,
errors: tuple[ErrorDetail, ...]
| list[ErrorDetail] = (),
raw: bytes | str | None = None,
tag: str | None = None,
hint: str | None = None,
docs_url: str | None = None,
)
StringTooLong
¶
StringTooLong(
message: str = "",
*,
error_code: str | None = None,
fields: tuple[str, ...] | list[str] = (),
status: int | None = None,
operation: str | None = None,
sobject: str | None = None,
method: str | None = None,
path: str | None = None,
request_id: str | None = None,
retryable: bool | None = None,
errors: tuple[ErrorDetail, ...]
| list[ErrorDetail] = (),
raw: bytes | str | None = None,
tag: str | None = None,
hint: str | None = None,
docs_url: str | None = None,
)
InvalidPicklistValue
¶
InvalidPicklistValue(
message: str = "",
*,
error_code: str | None = None,
fields: tuple[str, ...] | list[str] = (),
status: int | None = None,
operation: str | None = None,
sobject: str | None = None,
method: str | None = None,
path: str | None = None,
request_id: str | None = None,
retryable: bool | None = None,
errors: tuple[ErrorDetail, ...]
| list[ErrorDetail] = (),
raw: bytes | str | None = None,
tag: str | None = None,
hint: str | None = None,
docs_url: str | None = None,
)
RowLocked
¶
RowLocked(
message: str = "",
*,
error_code: str | None = None,
fields: tuple[str, ...] | list[str] = (),
status: int | None = None,
operation: str | None = None,
sobject: str | None = None,
method: str | None = None,
path: str | None = None,
request_id: str | None = None,
retryable: bool | None = None,
errors: tuple[ErrorDetail, ...]
| list[ErrorDetail] = (),
raw: bytes | str | None = None,
tag: str | None = None,
hint: str | None = None,
docs_url: str | None = None,
)
RecordSaveBlocked
¶
RecordSaveBlocked(
message: str = "",
*,
error_code: str | None = None,
fields: tuple[str, ...] | list[str] = (),
status: int | None = None,
operation: str | None = None,
sobject: str | None = None,
method: str | None = None,
path: str | None = None,
request_id: str | None = None,
retryable: bool | None = None,
errors: tuple[ErrorDetail, ...]
| list[ErrorDetail] = (),
raw: bytes | str | None = None,
tag: str | None = None,
hint: str | None = None,
docs_url: str | None = None,
)
Bases: RecordError
CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY; in practice also unhandled trigger exceptions.
FlowFailed
¶
FlowFailed(
message: str = "",
*,
error_code: str | None = None,
fields: tuple[str, ...] | list[str] = (),
status: int | None = None,
operation: str | None = None,
sobject: str | None = None,
method: str | None = None,
path: str | None = None,
request_id: str | None = None,
retryable: bool | None = None,
errors: tuple[ErrorDetail, ...]
| list[ErrorDetail] = (),
raw: bytes | str | None = None,
tag: str | None = None,
hint: str | None = None,
docs_url: str | None = None,
)
ApexActionFailed
¶
ApexActionFailed(
message: str = "",
*,
error_code: str | None = None,
fields: tuple[str, ...] | list[str] = (),
status: int | None = None,
operation: str | None = None,
sobject: str | None = None,
method: str | None = None,
path: str | None = None,
request_id: str | None = None,
retryable: bool | None = None,
errors: tuple[ErrorDetail, ...]
| list[ErrorDetail] = (),
raw: bytes | str | None = None,
tag: str | None = None,
hint: str | None = None,
docs_url: str | None = None,
)
Bases: RecordError
APEX_FAILED: an uncaught exception in an Apex invocable action (sf.actions.apex).
Salesforce fails every input of the request with it. message holds the exception text.
StorageLimitExceeded
¶
StorageLimitExceeded(
message: str = "",
*,
error_code: str | None = None,
fields: tuple[str, ...] | list[str] = (),
status: int | None = None,
operation: str | None = None,
sobject: str | None = None,
method: str | None = None,
path: str | None = None,
request_id: str | None = None,
retryable: bool | None = None,
errors: tuple[ErrorDetail, ...]
| list[ErrorDetail] = (),
raw: bytes | str | None = None,
tag: str | None = None,
hint: str | None = None,
docs_url: str | None = None,
)
EventPublishFailed
¶
EventPublishFailed(
message: str = "",
*,
error_code: str | None = None,
fields: tuple[str, ...] | list[str] = (),
status: int | None = None,
operation: str | None = None,
sobject: str | None = None,
method: str | None = None,
path: str | None = None,
request_id: str | None = None,
retryable: bool | None = None,
errors: tuple[ErrorDetail, ...]
| list[ErrorDetail] = (),
raw: bytes | str | None = None,
tag: str | None = None,
hint: str | None = None,
docs_url: str | None = None,
)
Bases: RecordError
Salesforce rejected a platform event publish (EventBus error).
error_code tells you why, for example LIMIT_EXCEEDED (the hourly publishing
allocation is used up) or PLATFORM_EVENT_PUBLISH_FAILED.
EventPublishUnavailable
¶
EventPublishUnavailable(
message: str = "",
*,
error_code: str | None = None,
fields: tuple[str, ...] | list[str] = (),
status: int | None = None,
operation: str | None = None,
sobject: str | None = None,
method: str | None = None,
path: str | None = None,
request_id: str | None = None,
retryable: bool | None = None,
errors: tuple[ErrorDetail, ...]
| list[ErrorDetail] = (),
raw: bytes | str | None = None,
tag: str | None = None,
hint: str | None = None,
docs_url: str | None = None,
)
Bases: EventPublishFailed
PLATFORM_EVENT_PUBLISHING_UNAVAILABLE: publishing is down for a moment (retryable).
LimitError
¶
LimitError(
message: str = "",
*,
error_code: str | None = None,
fields: tuple[str, ...] | list[str] = (),
status: int | None = None,
operation: str | None = None,
sobject: str | None = None,
method: str | None = None,
path: str | None = None,
request_id: str | None = None,
retryable: bool | None = None,
errors: tuple[ErrorDetail, ...]
| list[ErrorDetail] = (),
raw: bytes | str | None = None,
tag: str | None = None,
hint: str | None = None,
docs_url: str | None = None,
)
RequestLimitExceeded
¶
PubSubLimitExceeded
¶
PubSubLimitExceeded(
message: str = "",
*,
error_code: str | None = None,
fields: tuple[str, ...] | list[str] = (),
status: int | None = None,
operation: str | None = None,
sobject: str | None = None,
method: str | None = None,
path: str | None = None,
request_id: str | None = None,
retryable: bool | None = None,
errors: tuple[ErrorDetail, ...]
| list[ErrorDetail] = (),
raw: bytes | str | None = None,
tag: str | None = None,
hint: str | None = None,
docs_url: str | None = None,
)
Bases: LimitError
A Pub/Sub API allocation was hit (gRPC RESOURCE_EXHAUSTED).
error_code holds the Pub/Sub error code, for example one that ends in
concurrent.client.limit.exceeded, and request_id the rpcId.
BudgetExceeded
¶
BudgetExceeded(
message: str = "",
*,
usage: UsageSnapshot | None = None,
**kw: Any,
)
ServerError
¶
ServerError(
message: str = "",
*,
error_code: str | None = None,
fields: tuple[str, ...] | list[str] = (),
status: int | None = None,
operation: str | None = None,
sobject: str | None = None,
method: str | None = None,
path: str | None = None,
request_id: str | None = None,
retryable: bool | None = None,
errors: tuple[ErrorDetail, ...]
| list[ErrorDetail] = (),
raw: bytes | str | None = None,
tag: str | None = None,
hint: str | None = None,
docs_url: str | None = None,
)
PartialFailure
¶
PartialFailure(
message: str = "",
*,
results: BatchResult[Any] | None = None,
**kw: Any,
)
BulkJobFailed
¶
BulkJobFailed(
message: str = "",
*,
job_id: str | None = None,
state: str | None = None,
error_message: str | None = None,
**kw: Any,
)
Bases: SalesforceError
A Bulk 2.0 job ended in state Failed or Aborted.
state says which. error_message is the job's errorMessage, when Salesforce sent one.
BulkJobTimeout
¶
BulkJobTimeout(
message: str = "",
*,
job_id: str | None = None,
state: str | None = None,
**kw: Any,
)
Bases: SalesforceError
A Bulk 2.0 job didn't finish within the timeout of wait().
The job keeps running in Salesforce. state is the last state the client saw.
BulkJobNotComplete
¶
BulkJobNotComplete(
message: str = "",
*,
job_id: str | None = None,
state: str | None = None,
**kw: Any,
)
Bases: SalesforceError
Results were asked for before the Bulk 2.0 query job was JobComplete.
Salesforce serves query results only for a complete job. Call wait() first. state
is the last state the client saw.
ApexError
¶
GraphQLError
¶
GraphQLError(
message: str = "",
*,
graphql_errors: tuple[Mapping[str, Any], ...] = (),
data: Any = None,
**kw: Any,
)
Bases: SalesforceError
GraphQL response with an errors array.
Salesforce answers 200 OK with an errors array for a syntax error
(InvalidSyntax), an unknown object or field (ValidationError, also for a field the
user can't read) and a failure while fetching data or saving a mutation
(DataFetchingException).
.graphql_errors holds the entries as Salesforce sent them (message, locations,
paths, extensions). .errors holds them as :class:ErrorDetail, with
extensions.ErrorType as the error code, the message HTML-unescaped and the field path
in extended["path"]. .data holds the data that came with the errors: {}
when the document was rejected, or the fields that did resolve (the failed one is
None) after a DataFetchingException.
ReportRunFailed
¶
ReportRunFailed(
message: str = "",
*,
report_id: str | None = None,
instance_id: str | None = None,
**kw: Any,
)
Bases: SalesforceError
An asynchronous report run ended with status Error.
report_id and instance_id name the run. Salesforce doesn't say why; a common cause
is that the user lost access to the report after the run started.
ReportTimeout
¶
ReportTimeout(
message: str = "",
*,
report_id: str | None = None,
instance_id: str | None = None,
run_status: str | None = None,
**kw: Any,
)
Bases: SalesforceError
An asynchronous report run didn't finish within the timeout of instance().
The run keeps going in Salesforce. run_status is the last run status the client saw
("New" or "Running"); call instance() again with the same ids to keep waiting.
DeployFailed
¶
DeployFailed(
message: str = "",
*,
job_id: str | None = None,
state: str | None = None,
result: DeployResult | None = None,
**kw: Any,
)
Bases: SalesforceError
A Metadata API deployment failed, was canceled or deployed only some components.
Raised by DeployResult.raise_for_errors(). .result holds the full
:class:~even_simpler_salesforce.DeployResult; .errors has one entry per failed
component and per failed Apex test.
RetrieveFailed
¶
MetadataTimeout
¶
MetadataTimeout(
message: str = "",
*,
job_id: str | None = None,
state: str | None = None,
**kw: Any,
)
Bases: SalesforceError
A deployment or retrieve was still running when the client stopped waiting.
The job keeps running in Salesforce. .job_id and .state say which job and where it was.
PubSubError
¶
PubSubError(
message: str = "",
*,
error_code: str | None = None,
fields: tuple[str, ...] | list[str] = (),
status: int | None = None,
operation: str | None = None,
sobject: str | None = None,
method: str | None = None,
path: str | None = None,
request_id: str | None = None,
retryable: bool | None = None,
errors: tuple[ErrorDetail, ...]
| list[ErrorDetail] = (),
raw: bytes | str | None = None,
tag: str | None = None,
hint: str | None = None,
docs_url: str | None = None,
)
Bases: SalesforceError
A Pub/Sub API (gRPC) error with no more specific class.
error_code is the Pub/Sub error-code trailer, or the gRPC status name when there is
none. request_id is the rpcId that Salesforce Support asks for. operation is
"pubsub.subscribe", path is the topic and status is None.
ReplayUnavailable
¶
Bases: PubSubError
Salesforce rejected the replay id a subscription tried to resume from.
This happens when the id is older than the retention window (72 hours) or does not belong
to the topic. replay_id holds the rejected id. Pass on_invalid_replay="latest" or
"earliest" to sf.pubsub.subscribe() to resubscribe instead.
DeployNotCancelable
¶
DeployNotCancelable(
message: str = "",
*,
job_id: str | None = None,
state: str | None = None,
**kw: Any,
)
Bases: RequestError
Salesforce refused to cancel a deployment because it is already finalizing.
From API 65.0 a deployment in the FinalizingDeploy stage can't be canceled. Raised by
sf.metadata.cancel_deploy(). Wait for the deployment with deploy_status(wait=True)
instead. .job_id is the deployment id and .state the stage it was in.
SoapFault
¶
UnexpectedResponse
¶
UnexpectedResponse(
message: str = "",
*,
event_id: str | None = None,
replay_id: bytes | None = None,
**kw: Any,
)
Bases: SalesforceError
HTML pages (proxy, maintenance), non-JSON bodies or schema surprises.
For a Pub/Sub event that does not decode against its schema, event_id and
replay_id identify the event; both are None otherwise.
SalesforceWarning
¶
Bases: UserWarning
A warning Salesforce sent in a Warning response header.
Salesforce adds Warning: 299 - "<text>" to responses for requests that use a
deprecated API version (REST API Developer Guide, Warning Header). The client calls
warnings.warn(text, SalesforceWarning) once per distinct text per client family, so the
notice is seen once and not on every call. The text is also in the sf_warning field of
the sf.request event. Silence it or turn it into an error with the standard
:mod:warnings filters, for example warnings.simplefilter("error", esf.SalesforceWarning).
docs_url_for
¶
docs_url_for(cls: type[BaseException]) -> str | None
The troubleshooting entry for cls, e.g. .../errors/#invalidfield.
A user subclass (such as a class registered in error_tags) gets the entry of its
nearest library class.
EsfDeprecationWarning
¶
Bases: DeprecationWarning
Raised for deprecated even-simpler-salesforce features (§17.1).
Framework integrations¶
SalesforceIntegration
¶
SalesforceIntegration(
auth: Auth | None = None,
*,
client: AsyncSalesforce
| AsyncFakeSalesforce
| None = None,
store: AsyncTokenStore | None = None,
auth_for: Callable[[Request], Auth | Awaitable[Auth]]
| None = None,
on_summary: Callable[[Request, dict[str, Any]], None]
| None = None,
error_handlers: bool = False,
)
Client lifecycle, dependencies, per-request roll-up and error handlers for FastAPI.
Example
esf_app = SalesforceIntegration(esf.ClientCredentials(...)) app = FastAPI(lifespan=esf_app.lifespan) esf_app.init_app(app)
@app.get("/leads/{lead_id}") async def get_lead(lead_id: str, sf: Annotated[esf.AsyncSalesforce, Depends(esf_app.admin)]): return await sf.sobject("Lead").get(lead_id)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
auth
|
Auth | None
|
Login flow of the app-wide client. The integration builds
|
None
|
client
|
AsyncSalesforce | AsyncFakeSalesforce | None
|
A client you built yourself (to set |
None
|
store
|
AsyncTokenStore | None
|
Token store of the app-wide client (with |
None
|
auth_for
|
Callable[[Request], Auth | Awaitable[Auth]] | None
|
Returns the login flow of the user behind a request (sync or async), for the
:meth: |
None
|
on_summary
|
Callable[[Request, dict[str, Any]], None] | None
|
Called with the request and the |
None
|
error_handlers
|
bool
|
Map typed errors to JSON responses (see the FastAPI guide for the table). Off by default. |
False
|
client
property
¶
client: AsyncSalesforce
The app-wide client, for code outside a route (background tasks, startup hooks).
Raises:
| Type | Description |
|---|---|
RuntimeError
|
The app is not running (lifespan not entered). |
init_app
¶
Add the roll-up middleware (with on_summary) and the error handlers to app.
Call it before the app starts: Starlette builds its middleware stack on the first request or lifespan event and refuses changes after that.
lifespan
async
¶
lifespan(app: FastAPI) -> AsyncIterator[None]
Pass as FastAPI(lifespan=...): creates the client at startup and closes it at shutdown.
To run your own startup code too, enter it from your lifespan:
async with esf_app.lifespan(app): yield.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
|
user
async
¶
user(request: Request) -> AsyncSalesforce
Dependency: a child of the app-wide client logged in as the request's user.
Built with client.with_auth(auth_for(request), store=store): it shares the
connection pool, caches and usage counters, and loads the user's token from the store.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
No |
Salesforce
¶
Salesforce(
app: Flask | None = None,
*,
auth: Auth | None = None,
client: Salesforce | FakeSalesforce | None = None,
store: TokenStore | None = None,
on_summary: Callable[[Request, dict[str, Any]], None]
| None = None,
error_handlers: bool = False,
)
Flask extension: one shared client, a per-request roll-up and error handlers.
Supports the app factory pattern: create it once, then call :meth:init_app for each app.
Each app gets its own client; nothing app-specific is kept on the extension.
Example
sf_ext = Salesforce(auth=esf.ClientCredentials(...)) sf_ext.init_app(app)
@app.get("/leads/
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
app
|
Flask | None
|
Initialise this app now (same as calling :meth: |
None
|
auth
|
Auth | None
|
Login flow. Each :meth: |
None
|
client
|
Salesforce | FakeSalesforce | None
|
A client you built yourself (to set |
None
|
store
|
TokenStore | None
|
Token store of the client built from |
None
|
on_summary
|
Callable[[Request, dict[str, Any]], None] | None
|
Called with the request and the |
None
|
error_handlers
|
bool
|
Map typed errors to JSON responses (see the Flask guide for the table). Off by default. |
False
|
client
property
¶
client: Salesforce
The current app's client. Needs an app context (any view, CLI command or test).
Raises:
| Type | Description |
|---|---|
RuntimeError
|
Outside an app context, or :meth: |
init_app
¶
Create the app's client and register the request hooks and error handlers.
Testing¶
FakeSalesforce
¶
FakeSalesforce(
auth: Auth | None = None,
*,
api_version: str = DEFAULT_API_VERSION,
cursor_key: bytes | None = None,
observers: Iterable[Observer] = (),
budget: Budget | None = None,
key_prefixes: Mapping[str, str] | None = None,
clock: Callable[[], datetime] | None = None,
)
Bases: _FakeControls
In-memory stand-in for :class:even_simpler_salesforce.Salesforce in unit tests.
It is duck-typed: it has the real client's methods for records, query/search,
collections, request, limits, usage, with_auth and tagged, but it is not
a subclass. Use typing.cast where your code is type-checked against the real class.
Example
fake = FakeSalesforce() lead_id = fake.sobject("Lead").create({"LastName": "Doe", "Company": "Acme"}) fake.on_query("SELECT Id FROM Lead", rows=fake.records("Lead")) fake.fail_next("sobject.update", esf.ValidationRuleFailed("Street is required"))
Every call emits a sf.request event (so esf.capture() and observers work) and
is recorded in :attr:calls.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
auth
|
Auth | None
|
Not used to authenticate. Its |
None
|
api_version
|
str
|
API version used in record URLs and cursors. |
DEFAULT_API_VERSION
|
cursor_key
|
bytes | None
|
Sign cursors like the real client's |
None
|
observers
|
Iterable[Observer]
|
Event observers. |
()
|
budget
|
Budget | None
|
Budget guard, applied to the fake's own usage numbers. |
None
|
key_prefixes
|
Mapping[str, str] | None
|
Override the 3-character id prefix per sObject. |
None
|
clock
|
Callable[[], datetime] | None
|
Returns "now" (timezone-aware) for modification timestamps. |
None
|
usage
property
¶
Usage tracker; usage.snapshot() counts the fake's calls like the real client.
instance_url
property
¶
instance_url: str
StaticToken.instance_url or https:// + the auth's My Domain host, else
https://example.my.salesforce.com.
on_query
¶
on_query(
match: Match,
rows: RowsSpec = (),
*,
total_size: int | None = None,
times: int | None = None,
) -> QueryScript
Script the answer to a SOQL query (used by query, query_iter and count).
Queries are never executed: the fake has no SOQL engine. The newest matching script wins.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
match
|
Match
|
The SOQL text (compared with whitespace collapsed), a compiled regex
( |
required |
rows
|
RowsSpec
|
Rows to return, or a callable |
()
|
total_size
|
int | None
|
|
None
|
times
|
int | None
|
Match at most this many times ( |
None
|
Returns:
| Type | Description |
|---|---|
QueryScript
|
The script; its |
Example
fake.on_query("SELECT Id FROM Lead WHERE Status = 'Open'", rows=[{"Id": lead_id}])
on_search
¶
on_search(
match: Match,
rows: RowsSpec = (),
*,
times: int | None = None,
) -> QueryScript
Script the answer to search (SOSL) or parameterized_search (matched on q).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
match
|
Match
|
SOSL text, compiled regex or predicate (see :meth: |
required |
rows
|
RowsSpec
|
Records to return, or a callable |
()
|
times
|
int | None
|
Match at most this many times ( |
None
|
Returns:
| Type | Description |
|---|---|
QueryScript
|
The script. |
on_graphql
¶
on_graphql(
match: GraphQLMatch,
data: Any = None,
*,
nodes: Sequence[Any] | None = None,
path: str | None = None,
page_size: int = 10,
times: int | None = None,
) -> GraphQLScript
Script the answer to a GraphQL document (used by graphql and graphql_iter).
Documents are never executed. The newest matching script wins.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
match
|
GraphQLMatch
|
The document (compared with whitespace collapsed), a compiled regex
( |
required |
data
|
Any
|
The |
None
|
nodes
|
Sequence[Any] | None
|
Instead of |
None
|
path
|
str | None
|
Dotted path to the connection when |
None
|
page_size
|
int
|
Nodes per page when |
10
|
times
|
int | None
|
Match at most this many calls ( |
None
|
Returns:
| Type | Description |
|---|---|
GraphQLScript
|
The script; its |
Example
fake.on_graphql(re.compile(r"Lead"), nodes=[{"Id": lead_id}], path="uiapi.query.Lead")
on_report
¶
on_report(
report_id: str,
result: ResultSpec,
*,
describe: Mapping[str, Any] | None = None,
) -> ReportScript
Script a report for sf.reports (run, run_async, instance, describe).
Reports are never run. An asynchronous run finishes at once.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
report_id
|
str
|
Id of the report ( |
required |
result
|
ResultSpec
|
The run body Salesforce would return (deep-copied), a |
required |
describe
|
Mapping[str, Any] | None
|
The body of |
None
|
Returns:
| Type | Description |
|---|---|
ReportScript
|
The script; its |
Example
fake.on_report("00O000000000001AAA", body)
on_dashboard
¶
Script the body sf.reports.dashboards.get(dashboard_id) returns (deep-copied).
refresh() of a scripted dashboard returns id and statusUrl.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dashboard_id
|
str
|
Id of the dashboard ( |
required |
body
|
Mapping[str, Any]
|
Dashboard results: |
required |
on_request
¶
on_request(
method: str,
path: str | Pattern[str],
response: Any = None,
*,
times: int | None = None,
) -> None
Register a handler for sf.request(method, path, ...).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str
|
HTTP method, or |
required |
path
|
str | Pattern[str]
|
Path as passed to |
required |
response
|
Any
|
Value returned to the caller (deep-copied), a callable receiving a
:class: |
None
|
times
|
int | None
|
Match at most this many times ( |
None
|
on_action
¶
Register a handler for an invocable action (sf.actions.* and sf.run).
The handler runs once per input, so bulk calls get one result per input.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kind
|
str
|
|
required |
name
|
str
|
Action name, e.g. the Flow API name or the Apex class name. |
required |
outputs
|
Any
|
Output values (deep-copied), a callable |
None
|
times
|
int | None
|
Match at most this many calls ( |
None
|
Example
fake.on_action("flow", "Assign_Lead", lambda inputs: {"assignedTo": "005..."})
set_action_describe
¶
Set what actions.describe(kind, name) returns; the action also appears in list.
on_apex
¶
on_apex(
method: str,
path: str | Pattern[str],
response: Any = None,
*,
times: int | None = None,
) -> None
Register a handler for sf.apex.<method>(path, ...).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str
|
HTTP method, or |
required |
path
|
str | Pattern[str]
|
Path after |
required |
response
|
Any
|
Value returned to the caller (deep-copied), a callable receiving a
:class: |
None
|
times
|
int | None
|
Match at most this many times ( |
None
|
on_execute_anonymous
¶
on_execute_anonymous(
match: Match,
result: Any = None,
*,
times: int | None = None,
) -> QueryScript
Script the answer to sf.tooling.execute_anonymous(code). The code never runs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
match
|
Match
|
The Apex code (compared with whitespace collapsed), a compiled regex
( |
required |
result
|
Any
|
An |
None
|
times
|
int | None
|
Match at most this many times ( |
None
|
Returns:
| Type | Description |
|---|---|
QueryScript
|
The script; its |
set_completions
¶
Set what sf.tooling.completions(type) returns ({} otherwise).
fail_next
¶
fail_next(
operation: str,
error: BaseException | type[BaseException],
*,
sobject: str | None = None,
times: int = 1,
) -> None
Make the next call(s) of operation raise error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
operation
|
str
|
Real operation name ( |
required |
error
|
BaseException | type[BaseException]
|
Exception instance or class, e.g. |
required |
sobject
|
str | None
|
Only fail calls for this sObject. |
None
|
times
|
int
|
Number of consecutive matching calls to fail. |
1
|
Example
fake.fail_next("sobject.update", esf.ValidationRuleFailed("[ADDR] Street is required"))
reject
¶
reject(
sobject: str | None,
error: SalesforceError,
*,
when: Callable[[Mapping[str, Any]], bool] | None = None,
) -> None
Reject record writes (create/update/upsert, single and collections) with error.
Unlike :meth:fail_next this acts per record, so collection calls return a
BatchResult with RecordResult(ok=False, errors=...) for the rejected rows.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sobject
|
str | None
|
Restrict to this sObject ( |
required |
error
|
SalesforceError
|
The error to raise / report, e.g. |
required |
when
|
Callable[[Mapping[str, Any]], bool] | None
|
Predicate on the written field values (updates include |
None
|
set_api_usage
¶
Pretend a Sforce-Limit-Info: api-usage=used/max header was seen (drives budgets).
set_explain
¶
Plans returned by every later explain() call.
set_describe
¶
Set what sobject(name).describe() returns (otherwise a minimal one is synthesised).
set_list_view
¶
set_list_view(
sobject: str,
api_name: str,
*,
label: str | None = None,
where: Callable[[dict[str, Any]], bool] | None = None,
fields: Sequence[str] | None = None,
) -> ListView
Add a list view that ui.list_views lists and ui.list_records reads.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sobject
|
str
|
The object of the list view. |
required |
api_name
|
str
|
List view API name, like |
required |
label
|
str | None
|
The label; defaults to |
None
|
where
|
Callable[[dict[str, Any]], bool] | None
|
Selects the records: |
None
|
fields
|
Sequence[str] | None
|
Fields of each record in |
None
|
Example
fake.set_list_view("Lead", "OpenLeads", where=lambda r: r.get("Status") == "Open")
add
¶
Seed one record without recording a call. Returns its id (data["Id"] if given).
add_many
¶
Seed several records. Returns their ids.
published
¶
Copies of the platform events published to name (Order_Event__e), oldest first.
records
¶
Copies of every stored record of sobject (with attributes and Id).
record
¶
A copy of one stored record, or None.
add_file
¶
add_file(
data: bytes,
*,
filename: str,
title: str | None = None,
link_to: str | None = None,
) -> str
Seed one file (ContentDocument, ContentVersion and, with link_to, a link).
Does not record a call. Returns the ContentVersion id.
file_content
¶
The bytes stored for a ContentVersion (uploaded or seeded), or None.
add_metadata
¶
Seed one metadata component for metadata.retrieve, list_metadata and describe_metadata.
Does not record a call. Seeding the same type and name again replaces the component.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metadata_type
|
str
|
Type name, e.g. |
required |
full_name
|
str
|
Component name, e.g. |
required |
files
|
Mapping[str, bytes | str]
|
Paths in a retrieved zip and their content, e.g.
|
required |
Example
fake.add_metadata("ApexClass", "Invoice", {"classes/Invoice.cls": "public class Invoice {}"})
on_deploy
¶
on_deploy(
outcome: DeployOutcome, *, times: int | None = None
) -> None
Script how the next deployments end (the default is Succeeded).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
outcome
|
DeployOutcome
|
A :class: |
required |
times
|
int | None
|
Use it for at most this many deployments ( |
None
|
Example
fake.on_deploy(esf.DeployResult("0Af", "Failed", done=True, error_message="boom"))
deployed_zip
¶
The zip that metadata.deploy sent for deploy_id, or None.
new_id
¶
A fresh, valid-looking 18-character id with sobject's key prefix.
calls_for
¶
Calls of one operation (optionally for one sObject).
close
¶
Close the fake family (later calls raise TransportError). No-op on children.
with_auth
¶
with_auth(
auth: Auth,
*,
store: Any = None,
instance_url: str | None = None,
) -> FakeSalesforce
A child sharing the same records, scripts and call log.
tagged
¶
tagged(
caller: str | None = None,
priority: Priority | None = None,
) -> FakeSalesforce
A child whose calls carry caller / priority (visible in :attr:calls).
merge
¶
merge(
master_id: str,
duplicate_ids: Sequence[str],
*,
sobject: str,
) -> MergeResult
Delete the duplicates and point fields that held their ids at the master.
describe_global
¶
Lists every sObject the fake knows about.
query
¶
query(
soql: str,
*values: Any,
page_size: int | None = None,
include_deleted: bool = False,
model: Any = None,
) -> QueryResult[Any]
Return the first page of the scripted rows (page_size honoured, default 2000).
values fill {} placeholders exactly like the real client; scripts registered
with :meth:on_query match the resulting SOQL.
query_one
¶
Exactly one scripted row; NotFound for none, MultipleMatches for several.
query_first
¶
The first scripted row, or None.
explain
¶
Plans set with :meth:set_explain (an empty list otherwise).
query_more
¶
query_more(
cursor: Cursor | str,
*,
page_size: int | None = None,
model: Any = None,
) -> QueryResult[Any]
The page after cursor. Tampered/foreign cursors raise :class:MalformedQuery.
query_iter
¶
query_iter(
soql: str,
*values: Any,
page_size: int | None = None,
include_deleted: bool = False,
model: Any = None,
expand_children: bool = False,
) -> Iterator[Any]
Yield every scripted row, fetching "pages" lazily (one query_more call per page).
count
¶
totalSize of the scripted answer (total_size= or the number of rows).
parameterized_search
¶
parameterized_search(
q: str,
*,
sobjects: Sequence[str | Mapping[str, Any]]
| None = None,
fields: Sequence[str] | None = None,
limit: int | None = None,
**extra: Any,
) -> list[dict[str, Any]]
Rows scripted with :meth:on_search, matched against q.
graphql
¶
The data scripted with :meth:on_graphql for query.
graphql_iter
¶
graphql_iter(
query: str,
variables: Mapping[str, Any] | None = None,
*,
path: str,
) -> Iterator[Any]
Yield the nodes of the scripted connection, one graphql call per page.
Validates the query and path like the real client.
request
¶
request(
method: str,
path: str,
*,
params: Mapping[str, Any] | None = None,
json: Any = None,
content: bytes | None = None,
headers: Mapping[str, str] | None = None,
idempotent: bool | None = None,
operation: str = "raw",
) -> Any
Dispatch to a handler registered with :meth:on_request.
run
¶
run(action: Action[R]) -> R
Run a typed action stub against the handler registered with :meth:on_action.
limits
¶
Limits set with :meth:set_limits (a small default set otherwise).
AsyncFakeSalesforce
¶
AsyncFakeSalesforce(
auth: Auth | None = None,
*,
api_version: str = DEFAULT_API_VERSION,
cursor_key: bytes | None = None,
observers: Iterable[Observer] = (),
budget: Budget | None = None,
key_prefixes: Mapping[str, str] | None = None,
clock: Callable[[], datetime] | None = None,
)
Bases: _FakeControls
In-memory stand-in for :class:even_simpler_salesforce.AsyncSalesforce.
Same controls and behaviour as :class:FakeSalesforce (they share one implementation);
the client methods are coroutines and query_iter is an async iterator.
Example
async with AsyncFakeSalesforce() as fake: fake.on_query("SELECT Id FROM Lead", rows=[{"Id": fake.new_id("Lead")}]) page = await fake.query("SELECT Id FROM Lead")
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
auth
|
Auth | None
|
Not used to authenticate. Its |
None
|
api_version
|
str
|
API version used in record URLs and cursors. |
DEFAULT_API_VERSION
|
cursor_key
|
bytes | None
|
Sign cursors like the real client's |
None
|
observers
|
Iterable[Observer]
|
Event observers. |
()
|
budget
|
Budget | None
|
Budget guard, applied to the fake's own usage numbers. |
None
|
key_prefixes
|
Mapping[str, str] | None
|
Override the 3-character id prefix per sObject. |
None
|
clock
|
Callable[[], datetime] | None
|
Returns "now" (timezone-aware) for modification timestamps. |
None
|
FakeSObject
¶
FakeSObject(state: FakeState, who: Who, name: str)
Fake of sf.sobject(name). Same methods and signatures as the real one.
get
¶
get(
record_id: str,
fields: Sequence[str] | None = None,
*,
model: Any = None,
if_modified_since: datetime | None = None,
) -> Any
Return a stored record. Raises :class:~even_simpler_salesforce.NotFound when missing.
get_by_external_id
¶
get_by_external_id(
field: str,
value: str,
fields: Sequence[str] | None = None,
*,
model: Any = None,
) -> Any
Return the record whose field equals value.
describe
¶
The describe set with fake.set_describe or a minimal synthesised one.
updated
¶
Ids of records created or changed in [start, end].
deleted
¶
Records deleted in [start, end].
create
¶
create(
data: Mapping[str, Any],
*,
assignment_rule_id: str | bool | None = None,
duplicate_rules: DuplicateRules | None = None,
allow_save: bool | None = None,
) -> str
Store a new record and return its 18-character id.
update
¶
update(
record_id: str,
data: Mapping[str, Any],
*,
assignment_rule_id: str | bool | None = None,
duplicate_rules: DuplicateRules | None = None,
allow_save: bool | None = None,
if_unmodified_since: datetime | None = None,
) -> None
Merge data into a stored record. :class:NotFound / :class:Conflict like the real API.
AsyncFakeSObject
¶
AsyncFakeSObject(inner: FakeSObject)
Async twin of :class:FakeSObject.
get
async
¶
get(
record_id: str,
fields: Sequence[str] | None = None,
*,
model: Any = None,
if_modified_since: datetime | None = None,
) -> Any
See :meth:FakeSObject.get.
get_by_external_id
async
¶
get_by_external_id(
field: str,
value: str,
fields: Sequence[str] | None = None,
*,
model: Any = None,
) -> Any
See :meth:FakeSObject.get_by_external_id.
updated
async
¶
See :meth:FakeSObject.updated.
deleted
async
¶
See :meth:FakeSObject.deleted.
create
async
¶
create(
data: Mapping[str, Any],
*,
assignment_rule_id: str | bool | None = None,
duplicate_rules: DuplicateRules | None = None,
allow_save: bool | None = None,
) -> str
See :meth:FakeSObject.create.
update
async
¶
update(
record_id: str,
data: Mapping[str, Any],
*,
assignment_rule_id: str | bool | None = None,
duplicate_rules: DuplicateRules | None = None,
allow_save: bool | None = None,
if_unmodified_since: datetime | None = None,
) -> None
See :meth:FakeSObject.update.
FakeCollections
¶
FakeCollections(
state: FakeState, who: Who, concurrency: int = 4
)
Fake of sf.collections: real :class:BatchResult / :class:RecordResult values.
With all_or_none=True each chunk of 200 is rolled back and the first error raised;
earlier chunks stay committed, exactly like the real API.
create
¶
create(
rows: Iterable[Mapping[str, Any]],
*,
sobject: str | None = None,
all_or_none: bool = False,
concurrency: int | None = None,
assignment_rule_id: str | bool | None = None,
duplicate_rules: DuplicateRules | None = None,
allow_save: bool | None = None,
) -> BatchResult[RecordResult]
Create records. Rows need attributes.type or sobject=.
update
¶
update(
sobject: str,
rows: Iterable[Mapping[str, Any]],
*,
all_or_none: bool = False,
concurrency: int | None = None,
assignment_rule_id: str | bool | None = None,
duplicate_rules: DuplicateRules | None = None,
allow_save: bool | None = None,
) -> BatchResult[RecordResult]
Update records; each row needs Id.
upsert
¶
upsert(
sobject: str,
field: str,
rows: Iterable[Mapping[str, Any]],
*,
all_or_none: bool = False,
concurrency: int | None = None,
assignment_rule_id: str | bool | None = None,
duplicate_rules: DuplicateRules | None = None,
allow_save: bool | None = None,
) -> BatchResult[RecordResult]
Upsert records by external id field.
delete
¶
delete(
ids: Iterable[str],
*,
all_or_none: bool = False,
concurrency: int | None = None,
) -> BatchResult[RecordResult]
Delete records by id (any sObject).
AsyncFakeCollections
¶
AsyncFakeCollections(inner: FakeCollections)
Async twin of :class:FakeCollections.
create
async
¶
create(
rows: Iterable[Mapping[str, Any]],
*,
sobject: str | None = None,
all_or_none: bool = False,
concurrency: int | None = None,
assignment_rule_id: str | bool | None = None,
duplicate_rules: DuplicateRules | None = None,
allow_save: bool | None = None,
) -> BatchResult[RecordResult]
See :meth:FakeCollections.create.
update
async
¶
update(
sobject: str,
rows: Iterable[Mapping[str, Any]],
*,
all_or_none: bool = False,
concurrency: int | None = None,
assignment_rule_id: str | bool | None = None,
duplicate_rules: DuplicateRules | None = None,
allow_save: bool | None = None,
) -> BatchResult[RecordResult]
See :meth:FakeCollections.update.
upsert
async
¶
upsert(
sobject: str,
field: str,
rows: Iterable[Mapping[str, Any]],
*,
all_or_none: bool = False,
concurrency: int | None = None,
assignment_rule_id: str | bool | None = None,
duplicate_rules: DuplicateRules | None = None,
allow_save: bool | None = None,
) -> BatchResult[RecordResult]
See :meth:FakeCollections.upsert.
delete
async
¶
delete(
ids: Iterable[str],
*,
all_or_none: bool = False,
concurrency: int | None = None,
) -> BatchResult[RecordResult]
See :meth:FakeCollections.delete.
FakeFiles
¶
Fake of sf.files. Same arguments, validation and operation names as the real one.
upload
¶
upload(
source: bytes
| str
| PathLike[str]
| IO[bytes]
| Iterable[bytes],
*,
filename: str | None = None,
title: str | None = None,
link_to: str | None = None,
share_type: ShareType | None = None,
visibility: Visibility | None = None,
) -> str
Store the file in memory. Returns the new ContentVersion id.
download
¶
Yield a stream over the stored bytes of a ContentVersion.
download_bytes
¶
The stored bytes of a ContentVersion.
download_attachment
¶
The Body of an Attachment seeded with fake.add("Attachment", {"Body": b"..."}).
AsyncFakeFiles
¶
AsyncFakeFiles(inner: FakeFiles)
Async twin of :class:FakeFiles.
upload
async
¶
upload(
source: bytes
| str
| PathLike[str]
| IO[bytes]
| AsyncIterable[bytes],
*,
filename: str | None = None,
title: str | None = None,
link_to: str | None = None,
share_type: ShareType | None = None,
visibility: Visibility | None = None,
) -> str
See :meth:FakeFiles.upload. Async iterators are read in full.
download
async
¶
download(
content_version_id: str,
) -> AsyncIterator[AsyncFakeFileStream]
See :meth:FakeFiles.download.
download_bytes
async
¶
See :meth:FakeFiles.download_bytes.
download_attachment
async
¶
See :meth:FakeFiles.download_attachment.
FakeComposite
¶
Fake of sf.composite. Same builders, limits and results as the real client.
Subrequests act on the fake's records: fake.reject(...) and fake.on_query(...)
apply inside them, and fake.fail_next("composite.send", error) fails the whole call.
In :meth:tree, a child record gets its parent's id in <ParentType>Id (or
<Parent__c> for a custom parent) unless it sets the field itself.
builder
¶
See sf.composite.builder().
AsyncFakeComposite
¶
AsyncFakeComposite(inner: FakeComposite)
FakeBulk
¶
Fake of sf.bulk. Same arguments and validation as the real one.
ingest
¶
ingest(
sobject: str,
operation: IngestOperation,
*,
rows: Iterable[Mapping[str, Any]]
| str
| PathLike[str]
| bytes,
external_id_field: str | None = None,
line_ending: LineEnding = "LF",
column_delimiter: ColumnDelimiter = "COMMA",
columns: Sequence[str] | None = None,
) -> FakeIngestJob
Apply the rows to the store and return a finished job (operation bulk.ingest).
start_query
¶
Create a finished query job with the rows of fake.on_query (operation bulk.query).
Rows are flattened ("Owner.Name"), values become strings and empty values None.
query
¶
query(
soql: str,
*values: Any,
include_deleted: bool = False,
parallel_downloads: int = 1,
poll: Backoff | None = None,
timeout: float = 3600.0,
) -> Iterator[dict[str, str | None]]
Yield the rows scripted with fake.on_query as Bulk CSV rows (operation bulk.query).
Rows are flattened ("Owner.Name"), values become strings and empty values None.
query_job
¶
query_job(job_id: str) -> FakeQueryJob
The query job with this id, made by start_query() or query() on this fake.
Raises NotFound for an unknown id or an ingest job's id, as Salesforce does.
ingest_job
¶
The ingest job with these ids, made by ingest() on this fake.
Raises NotFound for an unknown id or a query job's id, as Salesforce does.
AsyncFakeBulk
¶
AsyncFakeBulk(inner: FakeBulk)
Async twin of :class:FakeBulk.
ingest
async
¶
ingest(
sobject: str,
operation: IngestOperation,
*,
rows: Iterable[Mapping[str, Any]]
| str
| PathLike[str]
| bytes,
external_id_field: str | None = None,
line_ending: LineEnding = "LF",
column_delimiter: ColumnDelimiter = "COMMA",
columns: Sequence[str] | None = None,
) -> AsyncFakeIngestJob
See :meth:FakeBulk.ingest.
start_query
async
¶
See :meth:FakeBulk.start_query.
ingest_job
async
¶
See :meth:FakeBulk.ingest_job.
FakeUi
¶
Fake of sf.ui. Same arguments, validation and operation names as the real one.
record
¶
record(
record_id: str,
fields: Sequence[str] | None = None,
layout_types: Sequence[LayoutType] | None = None,
modes: Sequence[Mode] | None = None,
) -> dict[str, Any]
The stored record in UI API form; fields must exist on the object.
object_info
¶
Object metadata built from the describe.
picklist_values
¶
The active picklistValues of each picklist field in the describe.
create_defaults
¶
Default values (each describe field's defaultValue) for a new record.
clone_defaults
¶
The stored record's values without its id and system fields.
AsyncFakeUi
¶
AsyncFakeUi(inner: FakeUi)
Async twin of :class:FakeUi.
record
async
¶
record(
record_id: str,
fields: Sequence[str] | None = None,
layout_types: Sequence[LayoutType] | None = None,
modes: Sequence[Mode] | None = None,
) -> dict[str, Any]
See :meth:FakeUi.record.
object_info
async
¶
See :meth:FakeUi.object_info.
picklist_values
async
¶
See :meth:FakeUi.picklist_values.
create_defaults
async
¶
See :meth:FakeUi.create_defaults.
clone_defaults
async
¶
See :meth:FakeUi.clone_defaults.
ListView
dataclass
¶
ListView(
id: str,
api_name: str,
label: str,
where: Callable[[dict[str, Any]], bool] | None,
fields: tuple[str, ...] | None,
)
A list view registered with fake.set_list_view.
key_prefix
¶
The 3-character key prefix for sobject (stable; derived for custom objects).
FakeCall
dataclass
¶
FakeCall(
operation: str,
sobject: str | None,
args: Mapping[str, Any],
caller: str | None = None,
priority: str = "normal",
error: BaseException | None = None,
)
One call made against a fake client.
Attributes:
| Name | Type | Description |
|---|---|---|
operation |
str
|
Operation name, as used by the real client ( |
sobject |
str | None
|
sObject type involved, if any. |
args |
Mapping[str, Any]
|
The call's arguments by name. |
caller |
str | None
|
Caller tag (from |
priority |
str
|
Call priority. |
error |
BaseException | None
|
The exception the call raised, if any. |
FakeRequest
dataclass
¶
FakeRequest(
method: str,
path: str,
params: Mapping[str, Any],
json: Any,
content: bytes | None,
headers: Mapping[str, str],
)
What a fake.on_request(...) handler receives.
Attributes:
| Name | Type | Description |
|---|---|---|
method |
str
|
Upper-case HTTP method. |
path |
str
|
Normalised path (relative to |
params |
Mapping[str, Any]
|
Query parameters. |
json |
Any
|
Decoded JSON body, if |
content |
bytes | None
|
Raw body, if |
headers |
Mapping[str, str]
|
Extra headers. |
QueryScript
dataclass
¶
QueryScript(
match: Match,
rows: RowsSpec,
total_size: int | None = None,
times: int | None = None,
kind: str = "query",
hits: int = 0,
)
A scripted answer for query/count/search (returned by fake.on_query).
Attributes:
| Name | Type | Description |
|---|---|---|
match |
Match
|
SOQL text (whitespace-insensitive), compiled regex, or predicate. |
rows |
RowsSpec
|
Rows, or a callable receiving the SOQL and returning rows. |
total_size |
int | None
|
|
times |
int | None
|
How many times the script may match ( |
kind |
str
|
|
hits |
int
|
How many times it matched so far. |
UnscriptedCall
¶
Bases: AssertionError
The code under test made a call the fake has no script or handler for.
Subclasses AssertionError on purpose: it signals a test-setup problem and is never
swallowed by except esf.SalesforceError.
record
¶
record(
path: str | Path,
transport: BaseTransport
| AsyncBaseTransport
| None = None,
*,
mask_ids: bool = True,
mask_emails: bool = True,
mask_phones: bool = True,
mask_hosts: bool = True,
mask_personal: bool = True,
extra_keys: frozenset[str] | set[str] = frozenset(),
) -> RecordingTransport
An httpx transport that records redacted exchanges to path (sync and async).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Fixture file to write. |
required |
transport
|
BaseTransport | AsyncBaseTransport | None
|
Transport to forward to (default: a real HTTP transport). |
None
|
mask_ids
|
bool
|
Replace Salesforce ids with consistent fake ids. |
True
|
mask_emails
|
bool
|
Replace e-mail addresses. |
True
|
mask_phones
|
bool
|
Replace phone/fax field values. |
True
|
mask_hosts
|
bool
|
Replace instance host names with |
True
|
mask_personal
|
bool
|
Replace names/addresses in records and literals in SOQL parameters. |
True
|
extra_keys
|
frozenset[str] | set[str]
|
Additional JSON/form keys to redact (custom fields with personal data). |
frozenset()
|
Returns:
| Type | Description |
|---|---|
RecordingTransport
|
The transport; pass it to |
replay
¶
An httpx.MockTransport serving the interactions recorded in path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Fixture written by :func: |
required |
match_query
|
bool
|
Require the query string to match too (default). SOQL/SOSL in |
True
|
repeat
|
bool
|
When all matching interactions were used, serve the last one again instead of
raising :class: |
False
|
Returns:
| Type | Description |
|---|---|
MockTransport
|
A transport usable with both |
MockTransport
|
|
RecordingTransport
¶
RecordingTransport(
path: str | Path,
transport: BaseTransport
| AsyncBaseTransport
| None = None,
*,
redactor: Redactor | None = None,
)
Bases: BaseTransport, AsyncBaseTransport
Forwards requests to a real transport and appends redacted exchanges to a fixture file.
Works with both httpx.Client and httpx.AsyncClient. The file is rewritten after every
exchange, so a crashed test run still leaves a usable fixture.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Fixture file to write (created or overwritten). |
required |
transport
|
BaseTransport | AsyncBaseTransport | None
|
The transport to forward to. Defaults to |
None
|
redactor
|
Redactor | None
|
Redaction settings. |
None
|
Redactor
¶
Redactor(
*,
mask_ids: bool = True,
mask_emails: bool = True,
mask_phones: bool = True,
mask_hosts: bool = True,
mask_personal: bool = True,
extra_keys: frozenset[str] | set[str] = frozenset(),
)
Scrubs secrets and personal data from recorded traffic (see the module docstring).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mask_ids
|
bool
|
Replace Salesforce record ids (consistently) with fake ones. |
True
|
mask_emails
|
bool
|
Replace e-mail addresses. |
True
|
mask_phones
|
bool
|
Replace values of |
True
|
mask_hosts
|
bool
|
Replace instance host names. |
True
|
mask_personal
|
bool
|
Replace names and postal addresses in sObject records, user names in JSON and XML, and literals in SOQL/SOSL query parameters. |
True
|
extra_keys
|
frozenset[str] | set[str]
|
More JSON/form keys whose values must be redacted (e.g. custom fields holding personal data). |
frozenset()
|
value
¶
Redact a decoded JSON value recursively.
in_record marks the fields of an sObject record (a JSON object with attributes).
ReplayMismatch
¶
Bases: AssertionError
A replayed client made a request that has no (unused) recorded interaction.
TokenStoreContract
¶
Contract tests for a sync :class:~even_simpler_salesforce.TokenStore.
Override the make_store fixture to return a factory for fresh stores.
make_store
¶
make_store() -> Callable[[], TokenStore]
Override: return a zero-argument callable creating a fresh, empty store.
test_load_missing_returns_none
¶
test_load_missing_returns_none(store: TokenStore) -> None
Loading an unknown key returns None.
test_round_trip
¶
test_round_trip(store: TokenStore) -> None
What is saved is what is loaded (all fields).
test_versions_increase
¶
test_versions_increase(store: TokenStore) -> None
Each save returns a strictly greater version.
test_cas_conflict
¶
test_cas_conflict(store: TokenStore) -> None
A stale expected_version raises TokenConflict and changes nothing.
test_cas_on_missing_key_conflicts
¶
test_cas_on_missing_key_conflicts(
store: TokenStore,
) -> None
Expecting a version for a key that has none raises TokenConflict.
test_delete_removes_both_tokens
¶
test_delete_removes_both_tokens(store: TokenStore) -> None
delete removes access and refresh token; deleting again is a no-op.
test_version_not_reused_after_delete
¶
test_version_not_reused_after_delete(
store: TokenStore,
) -> None
A save after delete gets a version no earlier save had, so a stale CAS conflicts.
test_keys_are_isolated
¶
test_keys_are_isolated(store: TokenStore) -> None
Writes to one key never affect another.
test_lock_is_usable
¶
test_lock_is_usable(store: TokenStore) -> None
lock(key), when implemented, is a context manager.
test_lock_excludes_a_second_holder
¶
test_lock_excludes_a_second_holder(
store: TokenStore,
) -> None
While one thread holds lock(key), another cannot enter it.
test_concurrent_cas_has_one_winner
¶
test_concurrent_cas_has_one_winner(
store: TokenStore,
) -> None
N threads CAS-saving against the same version: exactly one wins.
AsyncTokenStoreContract
¶
Contract tests for an :class:~even_simpler_salesforce.AsyncTokenStore.
Override the make_store fixture to return a factory (sync or async) for fresh stores.
make_store
¶
make_store() -> Callable[
[], AsyncTokenStore | Awaitable[AsyncTokenStore]
]
Override: return a zero-argument callable creating a fresh, empty store.
test_load_missing_returns_none
¶
Loading an unknown key returns None.
test_round_trip
¶
What is saved is what is loaded (all fields).
test_versions_increase
¶
Each save returns a strictly greater version.
test_cas_conflict
¶
A stale expected_version raises TokenConflict and changes nothing.
test_cas_on_missing_key_conflicts
¶
Expecting a version for a key that has none raises TokenConflict.
test_delete_removes_both_tokens
¶
delete removes access and refresh token; deleting again is a no-op.
test_version_not_reused_after_delete
¶
A save after delete gets a version no earlier save had, so a stale CAS conflicts.
test_keys_are_isolated
¶
Writes to one key never affect another.
test_lock_is_usable
¶
lock(key), when implemented, is an async context manager.
test_lock_excludes_a_second_holder
¶
While one task holds lock(key), another cannot enter it.
FakePubSub
¶
Fake of sf.pubsub on :class:~even_simpler_salesforce.testing.FakeSalesforce.
Emit events with :meth:emit and :meth:emit_change; fake.pubsub.subscribe(topic)
then yields them, like the real client. Differences from the real client:
- The fake has no history before the test:
replay="latest"and"earliest"both start at the first event emitted on the topic. - Iterating ends when every emitted event was yielded, instead of waiting for more.
- Change events carry field names in their
ChangeEventHeader(no bitmaps).
Example
fake.pubsub.emit_change("Account", "UPDATE", ["001..."], changed_fields=["Phone"]) with fake.pubsub.subscribe("/data/AccountChangeEvent") as events: for ev in events: handle(ev)
emit
¶
emit(
topic: str,
payload: Mapping[str, Any],
*,
event_id: str | None = None,
schema_id: str = _SCHEMA_ID,
change: ChangeHeader | None = None,
) -> PubSubEvent
Add an event to topic; subscriptions yield it in order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
topic
|
str
|
|
required |
payload
|
Mapping[str, Any]
|
The decoded event fields. |
required |
event_id
|
str | None
|
The event's |
None
|
schema_id
|
str
|
Reported as :attr: |
_SCHEMA_ID
|
change
|
ChangeHeader | None
|
The decoded header of a change event; prefer :meth: |
None
|
Returns:
| Type | Description |
|---|---|
PubSubEvent
|
The event as subscriptions will yield it, with a fresh replay id. |
emit_change
¶
emit_change(
entity: str,
change_type: ChangeType | str,
record_ids: Iterable[str] = (),
*,
changed_fields: Iterable[str] = (),
nulled_fields: Iterable[str] = (),
diff_fields: Iterable[str] = (),
values: Mapping[str, Any] | None = None,
topic: str | None = None,
transaction_key: str | None = None,
sequence_number: int = 1,
commit_user: str | None = None,
change_origin: str | None = None,
commit_timestamp: datetime | None = None,
) -> PubSubEvent
Add a Change Data Capture event.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entity
|
str
|
The sObject, e.g. |
required |
change_type
|
ChangeType | str
|
|
required |
record_ids
|
Iterable[str]
|
The changed records (empty for |
()
|
changed_fields
|
Iterable[str]
|
Field names, |
()
|
nulled_fields
|
Iterable[str]
|
Fields set to |
()
|
diff_fields
|
Iterable[str]
|
Long text fields sent as a diff. |
()
|
values
|
Mapping[str, Any] | None
|
Field values in the payload (leave out for gap events). |
None
|
topic
|
str | None
|
Defaults to the entity's channel, e.g. |
None
|
transaction_key
|
str | None
|
Defaults to a random key per event. |
None
|
sequence_number
|
int
|
Position in the transaction. |
1
|
commit_user
|
str | None
|
Id of the user who made the change. |
None
|
change_origin
|
str | None
|
Client that made the change. |
None
|
commit_timestamp
|
datetime | None
|
Defaults to the fake's clock. |
None
|
Returns:
| Type | Description |
|---|---|
PubSubEvent
|
The event as subscriptions will yield it. |
fail_next
¶
fail_next(
error: BaseException | type[BaseException],
*,
topic: str | None = None,
times: int = 1,
) -> None
Make the next read of a subscription raise error.
Like the real client, the error comes out of the for loop, for example
esf.ReplayUnavailable(...) or esf.PubSubLimitExceeded(...). Same as
fake.fail_next("pubsub.subscribe", error, sobject=topic).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
error
|
BaseException | type[BaseException]
|
The exception (instance or class). |
required |
topic
|
str | None
|
Only fail subscriptions to this topic. |
None
|
times
|
int
|
Number of reads to fail. |
1
|
subscribe
¶
subscribe(
topic: str,
*,
replay: Replay = "latest",
replay_store: ReplayStore | None = None,
on_invalid_replay: OnInvalidReplay = "raise",
batch_size: int = MAX_BATCH_SIZE,
) -> FakeSubscription
Same arguments and delivery rules as Salesforce.pubsub.subscribe.
ReplayStoreContract
¶
Contract tests for a sync :class:~even_simpler_salesforce.ReplayStore.
Override the make_store fixture to return a factory for fresh stores. Set
persistent = False for a store that is not shared between instances (like
:class:~even_simpler_salesforce.InMemoryReplayStore).
make_store
¶
make_store() -> Callable[[], ReplayStore]
Override: return a zero-argument callable creating a fresh, empty store.
test_load_missing_returns_none
¶
test_load_missing_returns_none(store: ReplayStore) -> None
An unknown key loads None.
test_round_trip
¶
test_round_trip(store: ReplayStore) -> None
What is saved is loaded byte for byte, as bytes.
test_save_overwrites
¶
test_save_overwrites(store: ReplayStore) -> None
A later save replaces the earlier position.
test_keys_are_independent
¶
test_keys_are_independent(store: ReplayStore) -> None
Orgs and topics never share a position.
test_positions_persist_across_instances
¶
test_positions_persist_across_instances(
make_store: Callable[[], ReplayStore],
) -> None
A store built again from the same settings resumes from the saved position.
test_concurrent_saves_to_different_keys
¶
test_concurrent_saves_to_different_keys(
store: ReplayStore,
) -> None
Saves from several threads (one subscription each) all land.
AsyncReplayStoreContract
¶
Contract tests for an :class:~even_simpler_salesforce.AsyncReplayStore.
make_store may return the store or an awaitable resolving to it.
make_store
¶
make_store() -> Callable[
[], AsyncReplayStore | Awaitable[AsyncReplayStore]
]
Override: return a zero-argument callable creating a fresh, empty store.
test_load_missing_returns_none
¶
An unknown key loads None.
test_round_trip
¶
What is saved is loaded byte for byte, as bytes.
test_save_overwrites
¶
A later save replaces the earlier position.
test_keys_are_independent
¶
Orgs and topics never share a position.
test_positions_persist_across_instances
¶
A store built again from the same settings resumes from the saved position.
plugin
¶
pytest plugin for apps using even-simpler-salesforce (auto-registered via pytest11).
Fixtures:
esf_fake: a fresh :class:~even_simpler_salesforce.testing.FakeSalesforce.esf_async_fake: a fresh :class:~even_simpler_salesforce.testing.AsyncFakeSalesforce.esf_replay: factoryesf_replay(path, **kwargs) -> httpx.MockTransport; relative paths resolve against the requesting test file's directory.esf_sandbox_auth: anAuthbuilt fromESF_SANDBOX_*variables (skips if unset).
Marker:
@pytest.mark.esf_sandbox: real-org test, skipped unlessESF_SANDBOX_ACCESS_TOKEN+ESF_SANDBOX_INSTANCE_URL, orESF_SANDBOX_DOMAIN+ESF_SANDBOX_CLIENT_ID+ESF_SANDBOX_CLIENT_SECRET(orESF_SANDBOX_USERNAME+ESF_SANDBOX_PRIVATE_KEY_FILE) are set.
Importing this module needs only pytest (respx is not required).