Skip to content

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 (ClientCredentials, WebServerFlow, JwtBearer, StaticToken, TokenProvider).

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 httpx.AsyncClient (never closed by the library).

None
store AsyncTokenStore | None

Token store. Defaults to an in-memory store shared by the family.

None
cache Cache | None

Describe cache (Cache protocol). Defaults to an in-memory LRU.

None
observers Iterable[Observer]

Event observers (see esf.observability).

()
budget Budget | None

API usage budget and guard.

None
retry RetryPolicy | None

Retry policy.

None
timeout Timeouts | None

HTTP timeouts (ignored when http_client is given).

None
max_concurrency int | None

Max in-flight requests for the whole family.

None
user_agent str | None

User-Agent header.

None
json Any

Object with dumps(obj) -> bytes and loads(bytes) to replace the JSON codec.

None
error_tags Mapping[str, type[SalesforceError]] | None

Map of [TAG] message prefixes to custom error classes (§8.4).

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 tagged() views; not with_auth() children).

None
describe_cache DescribeCacheConfig | None

Describe-cache settings.

None
log_soql Literal['hash', 'redacted']

"hash" (default) logs only soql_hash; "redacted" also logs the SOQL with literals replaced by ?.

'hash'
http2 bool

Enable HTTP/2 on the owned client (needs the [http2] extra).

False
client_name str | None

Sent as Sforce-Call-Options: client=<name> on every API call so admins can attribute API usage to this integration (letters, digits, _ . : -; max 64).

None
pubsub_endpoint str | None

host:port of the Pub/Sub API for sf.pubsub. Defaults to api.pubsub.salesforce.com:443; use api.deu.pubsub.salesforce.com:443 to keep data in transit in the EU.

None
default_namespace str | None

Namespace prefix of a managed package, sent as Sforce-Call-Options: defaultNamespace=<ns> on every API call. SOQL and record data can then name the package's fields without the prefix (botId__c, not battle__botId__c), and Salesforce leaves the prefix out of the field names in responses, so the keys of returned dicts change. Ignored by describe calls. 1-15 letters, digits or _, starting with a letter, without __.

None
update_mru bool | None

Sent as Sforce-Mru: updateMru=true|false on sf.sobject(...) create, get, get-by-external-id, update and upsert. False stops these calls from adding records to the user's Recently Viewed list, which Salesforce recommends for integration users. None (default) sends no header, and Salesforce updates the list. Needs api_version 60.0 or newer.

None

Raises:

Type Description
ValueError

An option is not valid, or update_mru is set with an api_version older than 60.0.

usage property

usage: UsageTracker

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

observers: ObserverHub

The observer hub shared by the client family; sf.observers.add(obs) adds one.

aclose async

aclose() -> None

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

"Lead", "Contact" or "Account".

required

Returns:

Type Description
MergeResult

The master id, the merged ids and the related records that moved.

Raises:

Type Description
ValueError

unsupported sobject, malformed ids, or not 1 to 2 distinct duplicates.

RecordError

Salesforce refused the merge; the subclass follows the status code.

describe_global async

describe_global(*, cached: bool = True) -> dict[str, Any]

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: None = None,
) -> QueryResult[dict[str, Any]]
query(
    soql: str,
    *values: Any,
    page_size: int | None = None,
    include_deleted: bool = False,
    model: type[M],
) -> QueryResult[M]
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. {} placeholders are filled with values, quoted safely.

required
*values Any

Values for the {} placeholders (same quoting as esf.soql). Without values the query is sent unchanged.

()
page_size int | None

Sforce-Query-Options: batchSize (200-2000; a hint, not a guarantee).

None
include_deleted bool

Use queryAll (deleted and archived rows).

False
model Any

Optional Pydantic model / dataclass for the rows.

None

query_one async

query_one(
    soql: str,
    *values: Any,
    include_deleted: bool = False,
    model: Any = None,
) -> Any

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 (.matches holds the Ids on the first page).

query_first async

query_first(
    soql: str,
    *values: Any,
    include_deleted: bool = False,
    model: Any = None,
) -> Any

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

explain(soql: str, *values: Any) -> list[QueryPlan]

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

count(soql: str, *values: Any) -> int

Run SELECT COUNT() ... and return totalSize; values as in :meth:query.

search async

search(sosl: str) -> list[dict[str, Any]]

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(
    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

graphql(
    query: str, variables: Mapping[str, Any] | None = None
) -> dict[str, Any]

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 errors array, even with 200 OK. .data holds any partial data that came with the errors.

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 $after.

required
variables Mapping[str, Any] | None

Values for the other variables (an after here sets the first cursor).

None
path str

Dotted path from data to the connection, e.g. "uiapi.query.Lead".

required

Raises:

Type Description
ValueError

the query doesn't declare $after, or path is malformed.

GraphQLError

a page has an errors array.

UnexpectedResponse

path isn't in the response or lacks edges/pageInfo.

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 sf.actions.flow(name, {...}).

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

limits() -> dict[str, Limit]

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 (ClientCredentials, WebServerFlow, JwtBearer, StaticToken, TokenProvider).

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 httpx.Client (never closed by the library).

None
store TokenStore | None

Token store. Defaults to an in-memory store shared by the family.

None
cache Cache | None

Describe cache (Cache protocol). Defaults to an in-memory LRU.

None
observers Iterable[Observer]

Event observers (see esf.observability).

()
budget Budget | None

API usage budget and guard.

None
retry RetryPolicy | None

Retry policy.

None
timeout Timeouts | None

HTTP timeouts (ignored when http_client is given).

None
max_concurrency int | None

Max in-flight requests for the whole family.

None
user_agent str | None

User-Agent header.

None
json Any

Object with dumps(obj) -> bytes and loads(bytes) to replace the JSON codec.

None
error_tags Mapping[str, type[SalesforceError]] | None

Map of [TAG] message prefixes to custom error classes (§8.4).

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 tagged() views; not with_auth() children).

None
describe_cache DescribeCacheConfig | None

Describe-cache settings.

None
log_soql Literal['hash', 'redacted']

"hash" (default) logs only soql_hash; "redacted" also logs the SOQL with literals replaced by ?.

'hash'
http2 bool

Enable HTTP/2 on the owned client (needs the [http2] extra).

False
client_name str | None

Sent as Sforce-Call-Options: client=<name> on every API call so admins can attribute API usage to this integration (letters, digits, _ . : -; max 64).

None
pubsub_endpoint str | None

host:port of the Pub/Sub API for sf.pubsub. Defaults to api.pubsub.salesforce.com:443; use api.deu.pubsub.salesforce.com:443 to keep data in transit in the EU.

None
default_namespace str | None

Namespace prefix of a managed package, sent as Sforce-Call-Options: defaultNamespace=<ns> on every API call. SOQL and record data can then name the package's fields without the prefix (botId__c, not battle__botId__c), and Salesforce leaves the prefix out of the field names in responses, so the keys of returned dicts change. Ignored by describe calls. 1-15 letters, digits or _, starting with a letter, without __.

None
update_mru bool | None

Sent as Sforce-Mru: updateMru=true|false on sf.sobject(...) create, get, get-by-external-id, update and upsert. False stops these calls from adding records to the user's Recently Viewed list, which Salesforce recommends for integration users. None (default) sends no header, and Salesforce updates the list. Needs api_version 60.0 or newer.

None

Raises:

Type Description
ValueError

An option is not valid, or update_mru is set with an api_version older than 60.0.

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: type[M],
    if_modified_since: None = None,
) -> M
get(
    record_id: str,
    fields: Sequence[str] | None = None,
    *,
    model: type[M],
    if_modified_since: datetime,
) -> M | 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

describe(*, cached: bool = True) -> dict[str, Any]

GET sobjects/{o}/describe, served from the describe cache when fresh.

metadata async

metadata() -> dict[str, Any]

GET sobjects/{o} (basic info and recent items).

updated async

updated(start: datetime, end: datetime) -> dict[str, Any]

GET sobjects/{o}/updated?start=&end=: ids updated in the window.

deleted async

deleted(start: datetime, end: datetime) -> dict[str, Any]

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

Sforce-Auto-Assign: an AssignmentRule id, or True/False.

None
duplicate_rules DuplicateRules | None

Sforce-Duplicate-Rule-Header: how the org's duplicate rules apply (:class:~even_simpler_salesforce.DuplicateRules). None sends nothing.

None
allow_save bool | None

Deprecated (removed in 0.7): use duplicate_rules=DuplicateRules(allow_save=...).

None

Raises:

Type Description
DuplicateDetected

A duplicate rule blocked the record, or alerted without allow_save.

TypeError

Both duplicate_rules and allow_save are passed.

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

Sforce-Auto-Assign: an AssignmentRule id, or True/False.

None
duplicate_rules DuplicateRules | None

Sforce-Duplicate-Rule-Header, as in :meth:create.

None
allow_save bool | None

Deprecated (removed in 0.7): use duplicate_rules=DuplicateRules(allow_save=...).

None
if_unmodified_since datetime | None

Send If-Unmodified-Since.

None

Raises:

Type Description
Conflict

The record changed after if_unmodified_since (HTTP 412).

TypeError

Both duplicate_rules and allow_save are passed.

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

Sforce-Auto-Assign: an AssignmentRule id, or True/False.

None
duplicate_rules DuplicateRules | None

Sforce-Duplicate-Rule-Header, as in :meth:create.

None
allow_save bool | None

Deprecated (removed in 0.7): use duplicate_rules=DuplicateRules(allow_save=...).

None

Raises:

Type Description
MultipleMatches

Several records have this value (HTTP 300).

InvalidField

data also sets field.

TypeError

Both duplicate_rules and allow_save are passed.

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 attributes.type.

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

Sforce-Auto-Assign on every chunk: an AssignmentRule id, or True/False. None sends nothing (Salesforce runs the active rule).

None
duplicate_rules DuplicateRules | None

Sforce-Duplicate-Rule-Header on every chunk (:class:~even_simpler_salesforce.DuplicateRules). None sends nothing.

None
allow_save bool | None

Deprecated (removed in 0.7): use duplicate_rules=DuplicateRules(allow_save=...).

None

Raises:

Type Description
TypeError

Both duplicate_rules and allow_save are passed.

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 Id of the record to change.

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

Sforce-Auto-Assign on every chunk: an AssignmentRule id, or True/False. None sends nothing (Salesforce runs the active rule).

None
duplicate_rules DuplicateRules | None

Sforce-Duplicate-Rule-Header on every chunk (:class:~even_simpler_salesforce.DuplicateRules). None sends nothing.

None
allow_save bool | None

Deprecated (removed in 0.7): use duplicate_rules=DuplicateRules(allow_save=...).

None

Raises:

Type Description
TypeError

Both duplicate_rules and allow_save are passed.

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

Sforce-Auto-Assign on every chunk: an AssignmentRule id, or True/False. None sends nothing (Salesforce runs the active rule).

None
duplicate_rules DuplicateRules | None

Sforce-Duplicate-Rule-Header on every chunk (:class:~even_simpler_salesforce.DuplicateRules). None sends nothing.

None
allow_save bool | None

Deprecated (removed in 0.7): use duplicate_rules=DuplicateRules(allow_save=...).

None

Raises:

Type Description
TypeError

Both duplicate_rules and allow_save are passed.

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.

retrieve async

retrieve(
    sobject: str,
    ids: Iterable[str],
    fields: Sequence[str],
    *,
    concurrency: int | None = None,
) -> list[dict[str, Any] | None]

POST composite/sobjects/{o} in chunks of 2,000. None for ids not found.

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: bytes, a path, a binary file object, or an iterator of bytes chunks. A path or a seekable file is read again if the request is resent. An iterator can be read only once, so the client never resends it.

required
filename str | None

File name stored as PathOnClient; Salesforce takes the file type from its extension. Defaults to the name of the path or file object. Required for bytes and iterators.

None
title str | None

Title shown in Salesforce. Defaults to filename.

None
link_to str | None

Record id to share the file with. Without share_type and visibility the client sets FirstPublishLocationId, and Salesforce links the file in the same request (as a viewer link, "V", visible to "AllUsers" in a test org; the documentation doesn't say).

None
share_type ShareType | None

"V" (viewer), "C" (collaborator) or "I" (inferred) for the link to link_to. Defaults to "V" if only visibility is given.

None
visibility Visibility | None

"AllUsers", "InternalUsers" or "SharedUsers" for the link.

None

Raises:

Type Description
ValueError

no file name, an invalid id, or share_type/visibility without link_to.

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 (068...).

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

download_bytes(content_version_id: str) -> bytes

The whole content of a ContentVersion as bytes.

This reads the file into memory. Use :meth:download for large files.

download_attachment async

download_attachment(attachment_id: str) -> bytes

The content of a legacy Attachment (GET sobjects/Attachment/{id}/Body) as bytes.

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 (069...), not of a version.

required
record_id str

Record, user, group or library to link the file to.

required
share_type ShareType

"V" (viewer), "C" (collaborator) or "I" (inferred).

'V'
visibility Visibility | None

"AllUsers", "InternalUsers" or "SharedUsers". None lets Salesforce choose.

None

list_for async

list_for(record_id: str) -> list[FileLink]

The files linked to a record, one :class:FileLink per ContentDocumentLink.

Runs one SOQL query on ContentDocumentLink (plus one call per further page).

AsyncFileStream

AsyncFileStream(response: Response, spec: RequestSpec)

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-Type of the file, if Salesforce sent one.

content_length int | None

Size in bytes from Content-Length, if Salesforce sent one.

aclose async

aclose() -> None

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 "Lead".

required
operation IngestOperation

"insert", "update", "upsert", "delete" or "hardDelete".

required
rows Iterable[Mapping[str, Any]] | str | PathLike[str] | bytes

The data: an iterable of dicts, the path of a CSV file, or CSV bytes. For dicts, the keys of the first row are the columns. None (or "") sets a field to null, and a missing key leaves the field unchanged. On insert, both give the field its default value. A CSV file must be UTF-8 and is streamed from disk; a byte order mark is removed.

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 upsert, not allowed otherwise.

None
line_ending LineEnding

"LF" or "CRLF": the line ending of your CSV, or the one the client writes for dict rows.

'LF'
column_delimiter ColumnDelimiter

The delimiter of your CSV, or the one the client writes: "COMMA", "TAB", "PIPE", "SEMICOLON", "CARET" or "BACKQUOTE".

'COMMA'

Returns:

Type Description
AsyncIngestJob

The job. Call wait() on it, then read its results.

Raises:

Type Description
ValueError

invalid arguments, the string "#N/A" in a row, a CSV that isn't UTF-8, has no data rows or uses the other line ending, or a record over 100 MB.

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. {} placeholders are filled with values, as in sf.query.

required
*values Any

Values for the {} placeholders.

()
include_deleted bool

Use queryAll: also deleted and archived records.

False

Returns:

Type Description
AsyncQueryJob

The job. Call wait() on it, then read rows() or pages().

Raises:

Type Description
ValueError

the query selects FIELDS(ALL) or FIELDS(CUSTOM), which query jobs don't support. The client raises it before it creates a job.

RequestError

Salesforce rejected the job, for example with 400 API_ERROR because the query selects compound address or geolocation fields. hint then names their components.

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. {} placeholders are filled with values, as in sf.query.

required
*values Any

Values for the {} placeholders.

()
include_deleted bool

Use queryAll: also deleted and archived records.

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 (resultPages, API 58.0 and later), so values above 5 don't download more. Pages that wait their turn are kept in temporary files, not in memory.

1
poll Backoff | None

How long to wait between status calls. Defaults to esf.Backoff().

None
timeout float

Seconds to wait for the job to finish.

DEFAULT_TIMEOUT

Raises:

Type Description
ValueError

the query selects FIELDS(ALL) or FIELDS(CUSTOM), which query jobs don't support. The client raises it before it creates a job.

RequestError

Salesforce rejected the job, for example with 400 API_ERROR because the query selects compound address or geolocation fields (also through FIELDS(STANDARD)). hint then names their components.

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

job_id isn't a record id.

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

job_ids is a string, not a sequence of ids.

ValueError

job_ids is empty, or an id isn't a record id.

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

expand_compound_fields(
    sobject: str, fields: Sequence[str]
) -> list[str]

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.

ids property

ids: tuple[str, ...]

The Salesforce job ids, one per part of at most 100 MB.

info property

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.

parts property

parts: tuple[BulkJobInfo, ...]

The status of each Salesforce job, in upload order.

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 esf.Backoff() (2 s, doubling up to 30 s).

None
timeout float

Seconds to wait in total.

DEFAULT_TIMEOUT

Raises:

Type Description
BulkJobFailed

a job ended Failed or Aborted. unprocessed_records() lists the rows that Salesforce didn't process.

BulkJobTimeout

the jobs didn't finish in time. They keep running; call wait() again to keep waiting.

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.

id property

id: str

The Salesforce job id. Pass it to sf.bulk.query_job() to open the job again.

info property

Status from the latest call: state, records_processed and timing.

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 esf.Backoff() (2 s, doubling up to 30 s).

None
timeout float

Seconds to wait in total.

DEFAULT_TIMEOUT

Raises:

Type Description
BulkJobFailed

the job ended Failed or Aborted.

BulkJobTimeout

the job didn't finish in time. It keeps running; call wait() again to keep waiting.

Example

info = await job.wait(timeout=3600) print(info.records_processed)

abort async

abort() -> BulkJobInfo

Abort the job if it isn't finished. Returns :attr:info.

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 JobComplete yet. Call :meth:wait first.

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 next_locator of the last page you handled. None starts at the first page.

None
max_records int | None

The most rows per page. Salesforce picks the size when it's None. Smaller pages mean less to download again after a restart.

None

Raises:

Type Description
BulkJobNotComplete

the job isn't JobComplete yet. Call :meth:wait first.

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

AsyncResultPage(
    locator: str | None,
    next_locator: str | None,
    size: int | None,
    f: IO[bytes],
)

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.

close

close() -> None

Delete the temporary file. pages() does it for you when it moves on.

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 ["Lead.Name", "Lead.Owner.Name"]. The call fails if the user can't read one of them.

None
layout_types Sequence[LayoutType] | None

"Full" or "Compact": return the fields on that layout. Pass either fields or layout_types: Salesforce refuses the two together.

None
modes Sequence[Mode] | None

"View", "Edit" or "Create": the layout mode for layout_types. Salesforce uses View when you leave it out.

None

Returns:

Type Description
dict[str, Any]

The record: apiName, id, fields ({"Name": {"value": ..., "displayValue": ...}}),

dict[str, Any]

childRelationships, recordTypeId, eTag, lastModifiedDate and

dict[str, Any]

systemModstamp. displayValue is the formatted value ("$1,500,000" for a

dict[str, Any]

currency, the label of a picklist value) and None for plain text.

Raises:

Type Description
ValueError

neither or both of fields and layout_types given, an unqualified field name, or an unknown layout type or mode.

NotFound

no record with this id, or the user can't see it.

InvalidField

a field in fields doesn't exist.

object_info async

object_info(
    name: str, *, cached: bool = True
) -> dict[str, Any]

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

False asks Salesforce even if the describe cache has a fresh copy.

True

Returns:

Type Description
dict[str, Any]

apiName, label, fields, recordTypeInfos, defaultRecordTypeId,

dict[str, Any]

childRelationships, themeInfo and more.

Raises:

Type Description
Forbidden

the object doesn't exist or the user can't access it (Salesforce answers 403 INSUFFICIENT_ACCESS for both).

InvalidType

the UI API doesn't support the object.

picklist_values async

picklist_values(
    name: str, record_type_id: str, *, cached: bool = True
) -> dict[str, Any]

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. object_info(name)["defaultRecordTypeId"] is the user's default; 012000000000000AAA is the master record type.

required
cached bool

False asks Salesforce even if the describe cache has a fresh copy.

True

Returns:

Type Description
dict[str, Any]

``{"picklistFieldValues": {"LeadSource": {"values": [...], "controllerValues": {...},

dict[str, Any]

"defaultValue": ...}}}``.

create_defaults async

create_defaults(
    name: str, record_type_id: str | None = None
) -> dict[str, Any]

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]

record (the default field values), layout and objectInfos.

clone_defaults async

clone_defaults(record_id: str) -> dict[str, Any]

GET ui-api/record-defaults/clone/{id}: the values and layout to clone a record.

Parameters:

Name Type Description Default
record_id str

The record to clone.

required

Returns:

Type Description
dict[str, Any]

record (the values for the copy, without its id), layout and objectInfos.

list_views async

list_views(name: str) -> dict[str, Any]

GET ui-api/list-info/{name}: the list views of an object the user can see.

Parameters:

Name Type Description Default
name str

sObject API name.

required

Returns:

Type Description
dict[str, Any]

lists (one entry per list view with apiName, label and id),

dict[str, Any]

count and paging tokens.

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 "AllOpenLeads", or "__Recent" for the records the user viewed most recently.

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 nextPageToken of the previous page.

None

Returns:

Type Description
dict[str, Any]

records (in UI API record form), count, nextPageToken (None on the

dict[str, Any]

last page) and listInfoETag.

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

revoke(
    token_key: str | None = None,
    *,
    auth: Auth | None = None,
) -> None

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 auth's).

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

userinfo async

userinfo() -> dict[str, Any]

GET /services/oauth2/userinfo for the current token.

introspect async

introspect(
    token_key: str | None = None,
    *,
    auth: Auth | None = None,
) -> dict[str, Any]

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

Raises:

Type Description
SessionExpired

the client uses StaticToken, which can't be refreshed.

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 example ValidationRuleFailed).
  • a list returns a BatchResult of ActionResult, one per input, in input order. Failed invocations don't raise; call raise_for_errors() to raise PartialFailure. 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 raises ValueError before 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: Inputs) -> dict[str, Any]
standard(
    name: str, inputs: Sequence[Inputs]
) -> BatchResult[ActionResult]
standard(
    name: str, inputs: Inputs | Sequence[Inputs]
) -> Any

POST actions/standard/{name}, for example chatterPost or emailSimple.

Parameters:

Name Type Description Default
name str

Standard action name.

required
inputs Inputs | Sequence[Inputs]

One input dict, or a list of them for a bulk invocation.

required

flow async

flow(api_name: str, inputs: Inputs) -> dict[str, Any]
flow(
    api_name: str, inputs: Sequence[Inputs]
) -> BatchResult[ActionResult]
flow(
    api_name: str, inputs: Inputs | Sequence[Inputs]
) -> Any

POST actions/custom/flow/{api_name}: run an autolaunched Flow.

Parameters:

Name Type Description Default
api_name str

Flow API name (with the namespace prefix for packaged flows).

required
inputs Inputs | Sequence[Inputs]

Flow input variables, or a list of them for a bulk invocation.

required

apex async

apex(class_name: str, inputs: Inputs) -> dict[str, Any]
apex(
    class_name: str, inputs: Sequence[Inputs]
) -> BatchResult[ActionResult]
apex(
    class_name: str, inputs: Inputs | Sequence[Inputs]
) -> Any

POST actions/custom/apex/{class_name}: run an @InvocableMethod.

Parameters:

Name Type Description Default
class_name str

The Apex class name, not the method name.

required
inputs Inputs | Sequence[Inputs]

Input fields, or a list of them for a bulk invocation.

required

list async

list(kind: str) -> list[dict[str, Any]]

GET actions/standard or GET actions/custom/{kind}: the actions of one kind.

Parameters:

Name Type Description Default
kind str

"standard", "flow", "apex" or another custom action type ("emailAlert", "quickAction", ...).

required

Returns:

Type Description
list[dict[str, Any]]

One dict per action (name, label, type, url).

describe async

describe(kind: str, name: str) -> dict[str, Any]

GET the action resource: its inputs and outputs with names and types.

Parameters:

Name Type Description Default
kind str

"standard", "flow", "apex" or another custom action type.

required
name str

Action name.

required

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 /services/apexrest, starting with / ("/orders/42").

required
params Mapping[str, Any] | None

Query-string parameters.

None
headers Mapping[str, str] | None

Extra request headers.

None
idempotent bool | None

True lets the client resend the call after a timeout or 5xx.

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 /services/apexrest, starting with /.

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

True lets the client resend the call after a timeout or 5xx.

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.

patch async

patch(
    path: str,
    json: Any = None,
    *,
    params: Mapping[str, Any] | None = None,
    headers: Mapping[str, str] | None = None,
    idempotent: bool | None = None,
) -> Any

PATCH /services/apexrest{path} with a JSON body. Arguments as in :meth:post.

delete async

delete(
    path: str,
    *,
    params: Mapping[str, Any] | None = None,
    headers: Mapping[str, str] | None = None,
    idempotent: bool | None = None,
) -> Any

DELETE /services/apexrest{path}. Arguments as in :meth:get.

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]

(kind, name), where kind is "standard", "flow" or "apex".

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 LeadStatus value of your org.

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

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 LeadSource on an existing contact.

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 converted_status is empty.

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. .results holds every row; rows of the failed call have extended["outcome"] set to "unknown" (they may have converted) or "rejected".

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

required
data Mapping[str, Any]

Field values of the event.

required

Returns:

Type Description
PublishResult

The queued event, with its uuid (EventUuid).

Raises:

Type Description
EventPublishFailed

Salesforce refused the event, for example LIMIT_EXCEEDED.

EventPublishUnavailable

publishing is down for a moment; try again later.

RecordError

another record error, such as RequiredFieldMissing.

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

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

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

tree(
    sobject: str, records: Iterable[Mapping[str, Any]]
) -> dict[str, str]

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]

{referenceId: id} for every record created.

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 RequiredFieldMissing), and .errors holds every entry with extended["referenceId"].

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.

subrequests property

subrequests: list[Subrequest]

The subrequests added so far, in order.

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 raise_for_errors().

Raises:

Type Description
ValueError

no subrequests were added.

create

create(
    sobject: str,
    data: Mapping[str, Any],
    *,
    ref_id: str | None = None,
) -> Reference

POST sobjects/{sobject}: create a record.

Parameters:

Name Type Description Default
sobject str

sObject API name.

required
data Mapping[str, Any]

Field values. A value may be a reference to an earlier result.

required
ref_id str | None

Reference id for this subrequest; generated when omitted.

None

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(
    sobject: str,
    record_id: str,
    *,
    ref_id: str | None = None,
) -> Reference

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

query(
    soql: str, *values: Any, ref_id: str | None = None
) -> Reference

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

request(
    method: str,
    path: str,
    *,
    body: Any = None,
    ref_id: str | None = None,
) -> Reference

Any other REST resource the request type supports, such as sObject Collections.

Parameters:

Name Type Description Default
method str

GET, POST, PATCH, PUT or DELETE.

required
path str

Path relative to /services/data/vXX.X/, e.g. "composite/sobjects".

required
body Any

JSON body (not for GET).

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.

graphs property

graphs: list[Graph]

The graphs added so far, in order.

send async

send() -> list[GraphResult]

POST composite/graph: run every graph in one round trip.

Returns:

Name Type Description
One list[GraphResult]

class:~even_simpler_salesforce.GraphResult per graph, in the order you added

list[GraphResult]

them. A failed graph doesn't raise; check .ok or call raise_for_errors().

Raises:

Type Description
ValueError

no graphs were added, or a graph has no subrequests.

graph

graph(graph_id: str | None = None) -> Graph

Add a graph and return it; add subrequests to the graph.

Parameters:

Name Type Description Default
graph_id str | None

Id for the graph (letters, digits and underscores); generated when omitted.

None

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.

subrequests property

subrequests: list[Subrequest]

The subrequests added so far, in order.

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

create(
    sobject: str,
    data: Mapping[str, Any],
    *,
    ref_id: str | None = None,
) -> Reference

POST sobjects/{sobject}: create a record.

Parameters:

Name Type Description Default
sobject str

sObject API name.

required
data Mapping[str, Any]

Field values. A value may be a reference to an earlier result.

required
ref_id str | None

Reference id for this subrequest; generated when omitted.

None

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(
    sobject: str,
    record_id: str,
    *,
    ref_id: str | None = None,
) -> Reference

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

query(
    soql: str, *values: Any, ref_id: str | None = None
) -> Reference

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

request(
    method: str,
    path: str,
    *,
    body: Any = None,
    ref_id: str | None = None,
) -> Reference

Any other REST resource the request type supports, such as sObject Collections.

Parameters:

Name Type Description Default
method str

GET, POST, PATCH, PUT or DELETE.

required
path str

Path relative to /services/data/vXX.X/, e.g. "composite/sobjects".

required
body Any

JSON body (not for GET).

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

ref

ref(field: str) -> str

@{referenceId.field}: Salesforce replaces it with that value of this result.

Parameters:

Name Type Description Default
field str

A field of the result body, such as "id" for a create or "records[0].Id" for a query.

required

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

"/event/Order_Event__e" for a platform event, or a change event channel such as "/data/AccountChangeEvent" or "/data/ChangeEvents".

required
replay Replay

Where to start when the store has no position: "latest" (new events only), "earliest" (everything retained, up to 72 hours) or a replay id to start after.

'latest'
replay_store AsyncReplayStore | None

Loads the start position and saves progress. Its key is "{org_id}:{topic}".

None
on_invalid_replay OnInvalidReplay

If Salesforce rejects the start position (for example it is older than 72 hours): "raise" raises :class:ReplayUnavailable; "latest" or "earliest" resubscribe from there.

'raise'
batch_size int

Most events requested but not yet consumed (1 to 100).

MAX_BATCH_SIZE

Returns:

Type Description
AsyncSubscription

An unopened subscription; async with opens the stream.

Raises:

Type Description
ValueError

a bad argument.

ImportError

the [pubsub] extra is not installed.

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.

token_key property

token_key: str

Key of this flow's record in the token store.

base_url property

base_url: str

Base URL of the OAuth endpoints, resolved from domain (see :func:resolve_domain).

token_url property

token_url: str

The OAuth token endpoint (/services/oauth2/token).

client_id_hash property

client_id_hash: str

Short SHA-256 prefix of client_id, used in events instead of the id.

static_token

static_token() -> Token | None

A token known without any request (StaticToken).

token_form

token_form(current: Token | None) -> dict[str, str]

Form for acquiring a new token, given the current one (may be None).

client_auth_form

client_auth_form() -> dict[str, str]

client_id (and client_secret when set) for OAuth form posts.

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.

token_key property

token_key: str

token_key if given, else a hash of the domain and client id.

token_form

token_form(current: Token | None) -> dict[str, str]

Client-credentials grant form.

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: "login", "test" or a My Domain URL.

required
client_id str

Consumer key, sent as the iss claim.

required
username str

The user to act as, sent as the sub claim.

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 repr().

None
audience str | None

The aud claim; inferred from domain when unset.

None
token_key str | None

Token store key.

None
refresh_ahead timedelta | None

Refresh proactively after this timedelta.

None
expiry Expiry

"introspect" reads the expiry from the introspection endpoint.

'unknown'

Raises:

Type Description
ImportError

The [jwt] extra isn't installed.

ValueError

The key is encrypted and private_key_passphrase is missing or wrong, or a passphrase was given for a key that isn't encrypted.

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 domain with a path prefix, or a *.my.site.com host): the site URL itself.
  • test, https://test.salesforce.com or a *.sandbox.my.salesforce.com host: 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

assertion(now: float | None = None) -> str

A freshly signed RS256 JWT assertion (iss, sub, aud, exp).

token_form

token_form(current: Token | None) -> dict[str, str]

JWT bearer grant form with a new assertion.

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}").

token_key property

token_key: str

The token_key passed to the constructor.

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

code_form(
    code: str, code_verifier: str | None
) -> dict[str, str]

Form for exchanging an authorization code (with the PKCE verifier, if any).

token_form

token_form(current: Token | None) -> dict[str, str]

Refresh-token grant form.

Raises:

Type Description
ReauthorizationRequired

no refresh token is stored.

TokenProvider dataclass

TokenProvider(
    get_token: Callable[[], Token],
    *,
    token_key: str | None = None,
)

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:Token with at least access_token, instance_url and issued_at. Set expires_at if you know it, and the client gets a new token within 60 seconds of that time. Raise an exception if it can't get a token. Don't put the token in the exception message: it isn't in RefreshFailed's message, but it is __cause__, which tracebacks print.

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

None

Raises:

Type Description
TypeError

get_token isn't callable, or is an async function.

token_key property

token_key: str

token_key if given, else token_provider:<random>, unique to this object.

client_id_hash property

client_id_hash: str

Always empty: a token provider has no OAuth client.

token_form

token_form(current: Token | None) -> dict[str, str]

Not used: the client calls get_token instead of the token endpoint.

StaticToken dataclass

StaticToken(access_token: str, instance_url: str)

Bases: Auth

A token obtained elsewhere. No refresh: a 401 raises :class:SessionExpired.

token_key property

token_key: str

A hash of the instance URL and the token.

client_id_hash property

client_id_hash: str

Always empty: a static token has no OAuth client.

static_token

static_token() -> Token | None

The token, built from the constructor arguments.

token_form

token_form(current: Token | None) -> dict[str, str]

Not supported: a static token can't be refreshed.

AuthStart dataclass

AuthStart(url: str, state: str, code_verifier: str | None)

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,
)

An OAuth token as issued by Salesforce.

repr() redacts access_token and refresh_token.

replace

replace(**changes: Any) -> Token

A copy with changes applied (dataclasses.replace).

Token stores

AsyncTokenStore

Bases: Protocol

Async token store.

Contract for durable stores:

  1. One record per Salesforce identity, not per app user.
  2. save with expected_version MUST be atomic (compare-and-swap or row lock).
  3. Refresh tokens SHOULD be encrypted at rest.
  4. delete MUST remove both tokens.

Use esf.testing.token_store_contract to check your implementation.

load async

load(key: str) -> Token | None

Return the stored token (with its version) for key, or None.

save async

save(
    key: str, token: Token, *, expected_version: int | None
) -> Token

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.

load

load(key: str) -> Token | None

Return the stored token (with its version) for key, or None.

save

save(
    key: str, token: Token, *, expected_version: int | None
) -> Token

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

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.

load async

load(key: str) -> Token | None

Return the stored token for key, or None.

save async

save(
    key: str, token: Token, *, expected_version: int | None
) -> Token

Store token with the next version; compare-and-swap when expected_version is given.

Raises:

Type Description
TokenConflict

expected_version doesn't match the stored version.

delete async

delete(key: str) -> None

Remove the token record for key (no-op if missing).

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

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.

load

load(key: str) -> Token | None

Return the stored token for key, or None.

save

save(
    key: str, token: Token, *, expected_version: int | None
) -> Token

Store token with the next version; compare-and-swap when expected_version is given.

Raises:

Type Description
TokenConflict

expected_version doesn't match the stored version.

delete

delete(key: str) -> None

Remove the token record for key (no-op if missing).

lock

lock(key: str) -> Iterator[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).

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:

  1. load returns exactly the bytes that the last save for that key stored.
  2. load of a key that was never saved returns None.
  3. save overwrites; keys are independent of each other.

Use esf.testing.replay_store_contract to check your implementation.

load async

load(key: str) -> bytes | None

The stored replay id for key, or None.

save async

save(key: str, replay_id: bytes) -> None

Store replay_id as the position for key, replacing any earlier value.

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:

  1. load returns exactly the bytes that the last save for that key stored.
  2. load of a key that was never saved returns None.
  3. save overwrites; keys are independent of each other.

Use esf.testing.replay_store_contract to check your implementation.

load

load(key: str) -> bytes | None

The stored replay id for key, or None.

save

save(key: str, replay_id: bytes) -> None

Store replay_id as the position for key, replacing any earlier value.

AsyncInMemoryReplayStore

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.

load async

load(key: str) -> bytes | None

The stored replay id for key, or None.

save async

save(key: str, replay_id: bytes) -> None

Store replay_id for key.

InMemoryReplayStore

InMemoryReplayStore()

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.

load

load(key: str) -> bytes | None

The stored replay id for key, or None.

save

save(key: str, replay_id: bytes) -> None

Store replay_id for key.

Query building

soql

soql(template: str, /, *args: Any, **kwargs: Any) -> str

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

soql_like(value: str, pattern: str = '{}') -> SoqlLiteral

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

sosl_term(value: str) -> str

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

value is empty or only whitespace (Salesforce rejects an empty search).

Cursor

Bases: str

Opaque pagination cursor. Treat it as a string; don't parse it.

flatten

flatten(row: Mapping[str, Any]) -> dict[str, Any]

Flatten one query row for CSV, DataFrames or JSON (§9.2).

  • attributes is 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

row is not a plain mapping: for example a list of rows, a QueryResult or a model instance from model=.

Results

QueryResult dataclass

QueryResult(
    records: list[T],
    total_size: int,
    done: bool,
    cursor: Cursor | None = None,
)

Bases: Generic[T]

One page of a SOQL query.

Attributes:

Name Type Description
records list[T]

Rows of this page (plain dicts unless model= was given).

total_size int

totalSize reported by Salesforce for the whole query.

done bool

True when this is the last page.

cursor Cursor | None

Opaque cursor for :meth:query_more, or None when done.

BatchResult dataclass

BatchResult(
    results: list[T],
    operation: str | None = None,
    sobject: str | None = None,
)

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

succeeded property

succeeded: list[T]

Results that succeeded (check not batch.failed for "every record succeeded").

ok property

ok: list[T]

Deprecated alias of :attr:succeeded; to be removed in 0.7.

It reads like a bool (if batch.ok:) but is a list, true when any record succeeded.

failed property

failed: list[T]

Results that failed.

raise_for_errors

raise_for_errors() -> None

Raise :class:PartialFailure if any record failed.

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

isSuccess from Salesforce.

outputs Mapping[str, Any]

outputValues. Usually empty when the invocation failed; a failed Flow interview still has Flow__InterviewGuid and Flow__InterviewStatus.

errors tuple[ErrorDetail, ...]

The error entries when it failed.

action_name str | None

actionName as Salesforce reports it.

UpsertResult dataclass

UpsertResult(id: str | None, created: bool)

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 LeadStatus value of the org, e.g. "Closed - Converted".

account_id str | None

Merge into this existing account instead of creating one.

contact_id str | None

Merge into this existing contact (needs account_id; not for person accounts).

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 (sendNotificationEmail).

overwrite_lead_source bool

Overwrite LeadSource on an existing contact.

Raises:

Type Description
ValueError

an id is not a 15- or 18-character Salesforce id, converted_status is empty, contact_id is set without account_id, or a text value contains control characters (XML can't carry them).

TypeError

a text value is not a str, or a flag is not a bool.

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 None when none was created.

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 EventUuid (from the OPERATION_ENQUEUED entry).

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. "/data/AccountChangeEvent".

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

ConsumerEvent.event.id as Salesforce sent it, or None when it was empty. On a platform event it is the EventUuid, the key to de-duplicate on. Change events carry one too, but Salesforce documents it for platform events only: de-duplicate change events on (change.transaction_key, change.sequence_number).

schema_id str

Id of the Avro schema the payload was written with.

payload Mapping[str, Any]

The decoded event. Change events keep their ChangeEventHeader here too.

change ChangeHeader | None

The decoded header of a change event, None for a platform 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. "Account".

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 (UPDATE and UNDELETE only).

nulled_fields tuple[str, ...]

Fields set to null by an update.

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. "com/salesforce/api/rest/68.0".

is_gap property

is_gap: bool

True for GAP_* events: they carry no field values.

is_overflow property

is_overflow: bool

True for GAP_OVERFLOW: re-sync every record of :attr:entity_name.

ChangeType

Bases: str, Enum

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.

is_gap property

is_gap: bool

True for every GAP_* value, including GAP_OVERFLOW.

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

content_document_id str

Id of the ContentDocument (the file).

latest_version_id str | None

Id of the latest published ContentVersion. Pass it to sf.files.download().

title str | None

Title of the file.

file_extension str | None

File extension without the dot, for example "pdf".

size int | None

Size of the latest version in bytes.

share_type str | None

"V" (viewer), "C" (collaborator) or "I" (inferred).

visibility str | None

"AllUsers", "InternalUsers" or "SharedUsers".

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:SubrequestResult per subrequest.

operation str | None

"composite.send", "composite.batch" or "composite.graph".

succeeded property

succeeded: list[SubrequestResult]

Subrequests that succeeded.

failed property

Subrequests that failed, including the ones Salesforce halted or rolled back.

raise_for_errors

raise_for_errors() -> None

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 (httpStatusCode or statusCode).

body Any

Decoded body of the subrequest: the record for a get, the query page for a query, {"id": ..., "success": true, ...} for a create, None for 204.

headers Mapping[str, str]

Response headers of the subrequest, such as Location.

error SalesforceError | None

The typed error for a failed subrequest (§8), else None.

ok property

ok: bool

Whether the subrequest succeeded.

halted property

halted: bool

Whether Salesforce skipped or rolled back this subrequest because another one failed.

errors property

errors: tuple[ErrorDetail, ...]

The error entries of a failed subrequest (empty when it succeeded).

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

isSuccessful from Salesforce.

results CompositeResult

The graph's subrequest results.

raise_for_errors

raise_for_errors() -> None

Raise the typed error of the subrequest that made this graph fail.

BulkJobState

Bases: str, Enum

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.

is_final property

is_final: bool

Whether the job has finished: JobComplete, Failed or Aborted.

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 (750...). For an ingest split over several jobs, the id of the first one.

operation str | None

insert, update, upsert, delete, hardDelete, query or queryAll.

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

numberRecordsProcessed.

records_failed int

numberRecordsFailed (ingest jobs only).

created_date datetime | None

When the job was created.

system_modstamp datetime | None

When Salesforce last changed the job.

total_processing_ms int | None

totalProcessingTime in milliseconds, if Salesforce sent it.

error_message str | None

errorMessage of a failed job.

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 sf__Error column: status code, message and fields.

id str | None

sf__Id: the record id, if Salesforce reported one.

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

"Index", "Other" or "TableScan" (leadingOperationType).

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

Limit(
    max: int,
    remaining: int,
    details: Mapping[str, Any] = (lambda: {})(),
)

One entry of GET /limits.

used property

used: int

max - remaining.

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

Timeouts(
    connect: float = 5.0,
    read: float = 60.0,
    write: float = 60.0,
    pool: float = 5.0,
)

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 (uniform(0, delay)).

respect_retry_after bool

Honour a Retry-After header when present.

max_retry_after float

A Retry-After longer than this is not waited for; the error is raised instead (with retry_after set) so the caller can decide.

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 sf.usage.threshold is emitted (once per threshold per UTC day).

pause_low_priority_above float | None

Raise :class:BudgetExceeded for priority="low" calls when the latest known usage fraction is above this value.

block_all_above float | None

Raise :class:BudgetExceeded for every call except priority="high" above this value.

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 If-None-Match (when Salesforce sent an ETag) and If-Modified-Since; a 304 keeps the entry.

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 DUPLICATES_DETECTED error, return fields of the matched records, not only their ids. :attr:DuplicateDetected.duplicates then carries them. Single-record writes only: sObject Collections errors carry no duplicate result.

run_as_current_user bool

Find duplicates with the sharing rules of the running user, not with system access.

Backoff dataclass

Backoff(
    start: float = 2.0,
    max: float = 30.0,
    factor: float = 2.0,
)

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.

delay

delay(attempt: int) -> float

The wait before poll number attempt (0-based).

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.

get

get(key: str) -> Any | None

Return the cached value for key, or None if missing or expired.

set

set(key: str, value: Any, ttl: float) -> None

Store value under key for ttl seconds.

delete

delete(key: str) -> None

Remove key (no-op if missing).

MemoryCache

MemoryCache(
    max_entries: int = 500, *, clock: Any = monotonic
)

Thread-safe in-memory cache with per-entry TTL and LRU eviction.

get

get(key: str) -> Any | None

Return the cached value for key, or None if missing or expired.

set

set(key: str, value: Any, ttl: float) -> None

Store value for ttl seconds; evicts the least recently used entry when full.

delete

delete(key: str) -> None

Remove key (no-op if missing).

clear

clear() -> None

Remove every entry.

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

Event(
    name: str,
    fields: Mapping[str, Any],
    timestamp: datetime = (lambda: now(utc))(),
)

A structured event. name is e.g. "sf.request"; fields never hold secrets.

get

get(key: str, default: Any = None) -> Any

Field key, or default when absent.

Observer

Bases: Protocol

Receives every event. MUST NOT raise; exceptions are swallowed and counted.

on_event

on_event(event: Event) -> None

Handle one event. Must be fast and must not raise.

capture

capture() -> Iterator[Summary]

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

Summary()

Accumulates sf.request events emitted inside a :func:capture block.

add

add(event: Event) -> None

Add one event to the roll-up (only sf.request and sf.auth.refreshed count).

as_fields

as_fields() -> dict[str, Any]

Flat fields for the app's own canonical log line.

StdlibLogging

StdlibLogging(
    logger: str | Logger = "esf", level: int = INFO
)

Log each event to a stdlib logger. Errors are logged at WARNING.

The fields are passed as extra={"esf": {...}} and also flattened into the message. The library never configures logging; attach handlers in your app.

on_event

on_event(event: Event) -> None

Log event on the configured logger.

Structlog

Structlog(logger: Any = None, name: str = 'esf')

Emit each event through a structlog logger as logger.info(event.name, **fields).

on_event

on_event(event: Event) -> None

Log event through 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.

on_event

on_event(event: Event) -> None

Record a span and metrics for each sf.request event, metrics for sf.pubsub.batch.

DebugPrinter

DebugPrinter(level: int = 1, stream: TextIO | None = None)

Prints one readable line per call to stderr.

on_event

on_event(event: Event) -> None

Print a readable line for event.

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 errorCode / OAuth error (e.g. "INVALID_FIELD").

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.update".

sobject str | None

sObject type involved, if any.

method str | None

HTTP method.

path str | None

Request path with ids replaced by :id.

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 ("[TAG] ..."), if any.

hint str | None

A likely fix, computed from data the client already had (never an API call). None when the library has nothing specific to say.

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,
)

Bases: SalesforceError

No usable HTTP response was received.

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,
)

Bases: TransportError

The connection could not be established; the request was never sent.

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,
)

Bases: TransportError

The request timed out.

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,
)

Bases: SalesforceError

Authentication or token problem.

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,
)

Bases: AuthError

401 that survived one refresh, or an expired :class:StaticToken.

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,
)

Bases: AuthError

The refresh token is expired, revoked or rotated out; the user must log in again.

RefreshFailed

RefreshFailed(
    message: str = "", *, ambiguous: bool = False, **kw: Any
)

Bases: AuthError

Token refresh failed. ambiguous=True when the outcome is unknown.

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,
)

Bases: AuthError

Compare-and-swap failure in a token store. Normally handled internally.

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

OAuthError(
    message: str = "",
    *,
    error: str | None = None,
    error_description: str | None = None,
    **kw: Any,
)

Bases: AuthError

Error returned by an OAuth endpoint ({"error", "error_description"}).

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,
)

Bases: SalesforceError

4xx caused by the request.

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,
)

Bases: RequestError

MALFORMED_QUERY, INVALID_QUERY_LOCATOR, or a rejected cursor.

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,
)

Bases: RequestError

INVALID_FIELD, INVALID_FIELD_FOR_INSERT_UPDATE, ...

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,
)

Bases: RequestError

INVALID_TYPE: unknown sObject type.

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,
)

Bases: RequestError

404 / NOT_FOUND / ENTITY_IS_DELETED.

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,
)

Bases: RequestError

INSUFFICIENT_ACCESS*, API_DISABLED_FOR_ORG, ...

MultipleMatches

MultipleMatches(
    message: str = "",
    *,
    matches: tuple[str, ...] = (),
    **kw: Any,
)

Bases: RequestError

HTTP 300: an external id matched several records. See .matches.

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,
)

Bases: RequestError

409 / 412 / 428.

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,
)

Bases: RequestError

410: resource retired or removed.

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,
)

Bases: RequestError

414 / 431: URI or headers too large.

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 configured api_version. A version newer than the org's release is not reported this way: Salesforce answers 404 NOT_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 newer api_version than 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,
)

Bases: SalesforceError

DML rejected by the org.

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,
)

Bases: RecordError

REQUIRED_FIELD_MISSING.

DuplicateDetected

DuplicateDetected(
    message: str = "", *, duplicates: Any = None, **kw: Any
)

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,
)

Bases: RecordError

INVALID_CROSS_REFERENCE_KEY, FIELD_INTEGRITY_EXCEPTION.

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,
)

Bases: RecordError

STRING_TOO_LONG.

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,
)

Bases: RecordError

INVALID_OR_NULL_FOR_RESTRICTED_PICKLIST.

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,
)

Bases: RecordError

UNABLE_TO_LOCK_ROW (retryable).

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,
)

Bases: RecordError

CANNOT_EXECUTE_FLOW_TRIGGER.

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,
)

Bases: RecordError

STORAGE_LIMIT_EXCEEDED.

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,
)

Bases: SalesforceError

A Salesforce or library-side limit was hit.

RequestLimitExceeded

RequestLimitExceeded(
    message: str = "",
    *,
    retry_after: float | None = None,
    **kw: Any,
)

Bases: LimitError

REQUEST_LIMIT_EXCEEDED (HTTP 403) or HTTP 429. .retry_after in seconds if known.

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,
)

Bases: LimitError

Raised by the library's own budget guard. .usage holds the current snapshot.

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,
)

Bases: SalesforceError

500 / 502 / 503 / SERVER_UNAVAILABLE.

PartialFailure

PartialFailure(
    message: str = "",
    *,
    results: BatchResult[Any] | None = None,
    **kw: Any,
)

Bases: SalesforceError

Some records of an allOrNone=false batch failed. .results holds the batch.

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

ApexError(
    message: str = "", *, body: Any = None, **kw: Any
)

Bases: SalesforceError

APEX_ERROR or an error returned by an Apex REST class. .body holds the body.

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

RetrieveFailed(
    message: str = "",
    *,
    job_id: str | None = None,
    state: str | None = None,
    **kw: Any,
)

Bases: SalesforceError

A Metadata API retrieve ended in state Failed. .job_id is the retrieve id.

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

ReplayUnavailable(
    message: str = "",
    *,
    replay_id: bytes | None = None,
    **kw: Any,
)

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

SoapFault(
    message: str = "",
    *,
    fault_code: str | None = None,
    **kw: Any,
)

Bases: SalesforceError

A SOAP fault that could not be mapped to a more specific class.

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 AsyncSalesforce(auth, store=store) at startup. Give auth or client.

None
client AsyncSalesforce | AsyncFakeSalesforce | None

A client you built yourself (to set cursor_key=, observers=, ...), or a fake in tests. The integration closes it at shutdown.

None
store AsyncTokenStore | None

Token store of the app-wide client (with auth) and of the per-user clients. Defaults to the app-wide client's store.

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:user dependency. Usually a WebServerFlow with a per-user token_key.

None
on_summary Callable[[Request, dict[str, Any]], None] | None

Called with the request and the esf.capture() roll-up fields (sf_calls, sf_ms, ...) after every HTTP request.

None
error_handlers bool

Map typed errors to JSON responses (see the FastAPI guide for the table). Off by default.

False

client property

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

init_app(app: FastAPI) -> None

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

on_summary or error_handlers is set but :meth:init_app was not called.

admin

admin() -> AsyncSalesforce

Dependency: the app-wide client (Depends(esf_app.admin)).

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 auth_for was configured.

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/") def get_lead(lead_id): return sf_ext.client.sobject("Lead").get(lead_id)

Parameters:

Name Type Description Default
app Flask | None

Initialise this app now (same as calling :meth:init_app).

None
auth Auth | None

Login flow. Each :meth:init_app builds Salesforce(auth, store=store). Give auth or client.

None
client Salesforce | FakeSalesforce | None

A client you built yourself (to set cursor_key=, observers=, ...), or a fake in tests. Closed when the process exits.

None
store TokenStore | None

Token store of the client built from auth.

None
on_summary Callable[[Request, dict[str, Any]], None] | None

Called with the request and the esf.capture() roll-up fields (sf_calls, sf_ms, ...) when each request is torn down.

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 was not called for the app.

init_app

init_app(app: Flask) -> None

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 instance_url (StaticToken) or My Domain base_url sets :attr:instance_url; otherwise a default instance is used.

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

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

calls property

calls: list[FakeCall]

Every call made through this fake family, in order.

usage property

usage: UsageTracker

Usage tracker; usage.snapshot() counts the fake's calls like the real client.

api_version property

api_version: str

The API version the fake pretends to use.

observers property

observers: ObserverHub

Observers receiving the fake's sf.request events.

closed property

closed: bool

Whether :meth:close was called on the root fake.

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 (re.search), or a predicate (soql) -> bool.

required
rows RowsSpec

Rows to return, or a callable (soql) -> rows evaluated per call (e.g. lambda q: fake.records("Lead")). Rows lacking attributes get them.

()
total_size int | None

totalSize to report; defaults to len(rows). count() returns it.

None
times int | None

Match at most this many times (None = unlimited).

None

Returns:

Type Description
QueryScript

The script; its hits attribute counts how often it matched.

Example

fake.on_query("SELECT Id FROM Lead WHERE Status = 'Open'", rows=[{"Id": lead_id}])

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:on_query).

required
rows RowsSpec

Records to return, or a callable (sosl) -> rows.

()
times int | None

Match at most this many times (None = unlimited).

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 (re.search), or a predicate (query) -> bool.

required
data Any

The data member to return (deep-copied), a callable (query, variables) -> data, or an exception to raise, such as esf.GraphQLError(...).

None
nodes Sequence[Any] | None

Instead of data: the nodes of a connection. The fake builds the connection at path with edges, pageInfo and totalCount, and pages it by the after variable.

None
path str | None

Dotted path to the connection when nodes is given ("uiapi.query.Lead").

None
page_size int

Nodes per page when nodes is given.

10
times int | None

Match at most this many calls (None = unlimited).

None

Returns:

Type Description
GraphQLScript

The script; its hits attribute counts how often it matched.

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 (00O...).

required
result ResultSpec

The run body Salesforce would return (deep-copied), a ReportResult, a callable (filters, include_details) -> body, or an exception to raise. For a body, include_details=False drops the detail rows.

required
describe Mapping[str, Any] | None

The body of describe(). Defaults to the reportMetadata of result.

None

Returns:

Type Description
ReportScript

The script; its runs attribute counts the runs.

Example

fake.on_report("00O000000000001AAA", body)

on_dashboard

on_dashboard(
    dashboard_id: str, body: Mapping[str, Any]
) -> None

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 (01Z...).

required
body Mapping[str, Any]

Dashboard results: dashboardMetadata, componentData, ...

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 "*" for any.

required
path str | Pattern[str]

Path as passed to request (relative or absolute /services/...; a versioned /services/data/vXX.X/ prefix is ignored), or a regex matched against the normalised path with fullmatch.

required
response Any

Value returned to the caller (deep-copied), a callable receiving a :class:FakeRequest, or an exception instance to raise.

None
times int | None

Match at most this many times (None = unlimited).

None

on_action

on_action(
    kind: str,
    name: str,
    outputs: Any = None,
    *,
    times: int | None = None,
) -> None

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

"standard", "flow" or "apex".

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 (inputs) -> outputs, or a SalesforceError instance. An error, raised or given, fails that invocation: a single call raises it, a bulk call reports it in its ActionResult.

None
times int | None

Match at most this many calls (None = unlimited).

None
Example

fake.on_action("flow", "Assign_Lead", lambda inputs: {"assignedTo": "005..."})

set_action_describe

set_action_describe(
    kind: str, name: str, describe: Mapping[str, Any]
) -> None

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 "*" for any.

required
path str | Pattern[str]

Path after /services/apexrest ("/orders/submit"), or a regex matched against it with fullmatch.

required
response Any

Value returned to the caller (deep-copied), a callable receiving a :class:FakeRequest (its path is the full /services/apexrest/... path), or an exception instance to raise, such as esf.ApexError(...).

None
times int | None

Match at most this many times (None = unlimited).

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 (re.search) or a predicate (code) -> bool. The newest match wins.

required
result Any

An esf.AnonymousResult (default: compiled and successful), a callable (code) -> AnonymousResult, or an exception instance to raise. Its log is returned only when the call passes capture_log=True.

None
times int | None

Match at most this many times (None = unlimited).

None

Returns:

Type Description
QueryScript

The script; its hits attribute counts how often it matched.

set_completions

set_completions(
    type: str, completions: Mapping[str, Any]
) -> None

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 ("sobject.update", "query", "query_more", "collections.create", "limits", "raw"...), or "*" for any.

required
error BaseException | type[BaseException]

Exception instance or class, e.g. esf.ValidationRuleFailed("Street is required").

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 (None = any).

required
error SalesforceError

The error to raise / report, e.g. esf.ValidationRuleFailed(...).

required
when Callable[[Mapping[str, Any]], bool] | None

Predicate on the written field values (updates include Id).

None

set_limits

set_limits(limits: Mapping[str, Limit]) -> None

Replace what limits() returns.

set_api_usage

set_api_usage(used: int, max: int) -> None

Pretend a Sforce-Limit-Info: api-usage=used/max header was seen (drives budgets).

set_explain

set_explain(plans: Iterable[QueryPlan]) -> None

Plans returned by every later explain() call.

set_describe

set_describe(
    sobject: str, describe: Mapping[str, Any]
) -> None

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 "AllOpenLeads".

required
label str | None

The label; defaults to api_name.

None
where Callable[[dict[str, Any]], bool] | None

Selects the records: (record) -> bool. None selects all of them.

None
fields Sequence[str] | None

Fields of each record in list_records; None returns every field.

None
Example

fake.set_list_view("Lead", "OpenLeads", where=lambda r: r.get("Status") == "Open")

add

add(sobject: str, data: Mapping[str, Any]) -> str

Seed one record without recording a call. Returns its id (data["Id"] if given).

add_many

add_many(
    sobject: str, rows: Iterable[Mapping[str, Any]]
) -> list[str]

Seed several records. Returns their ids.

published

published(name: str) -> list[dict[str, Any]]

Copies of the platform events published to name (Order_Event__e), oldest first.

records

records(sobject: str) -> list[dict[str, Any]]

Copies of every stored record of sobject (with attributes and Id).

record

record(
    sobject: str, record_id: str
) -> dict[str, Any] | None

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

file_content(content_version_id: str) -> bytes | None

The bytes stored for a ContentVersion (uploaded or seeded), or None.

add_metadata

add_metadata(
    metadata_type: str,
    full_name: str,
    files: Mapping[str, bytes | str],
) -> None

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. "ApexClass".

required
full_name str

Component name, e.g. "Invoice" ("Folder/Name" for folder types).

required
files Mapping[str, bytes | str]

Paths in a retrieved zip and their content, e.g. {"classes/Invoice.cls": "...", "classes/Invoice.cls-meta.xml": "..."}.

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:~even_simpler_salesforce.DeployResult (its id is replaced by the deployment's), or a callable (zip_bytes, options) -> DeployResult.

required
times int | None

Use it for at most this many deployments (None = every later one).

None
Example

fake.on_deploy(esf.DeployResult("0Af", "Failed", done=True, error_message="boom"))

deployed_zip

deployed_zip(deploy_id: str) -> bytes | None

The zip that metadata.deploy sent for deploy_id, or None.

new_id

new_id(sobject: str) -> str

A fresh, valid-looking 18-character id with sobject's key prefix.

calls_for

calls_for(
    operation: str, *, sobject: str | None = None
) -> list[FakeCall]

Calls of one operation (optionally for one sObject).

reset_calls

reset_calls() -> None

Forget recorded calls.

close

close() -> None

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

sobject

sobject(name: str) -> FakeSObject

Operations on one sObject type.

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

describe_global(*, cached: bool = True) -> dict[str, Any]

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

query_one(
    soql: str,
    *values: Any,
    include_deleted: bool = False,
    model: Any = None,
) -> Any

Exactly one scripted row; NotFound for none, MultipleMatches for several.

query_first

query_first(
    soql: str,
    *values: Any,
    include_deleted: bool = False,
    model: Any = None,
) -> Any

The first scripted row, or None.

explain

explain(soql: str, *values: Any) -> list[QueryPlan]

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

count(soql: str, *values: Any) -> int

totalSize of the scripted answer (total_size= or the number of rows).

search

search(sosl: str) -> list[dict[str, Any]]

Rows scripted with :meth:on_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

graphql(
    query: str, variables: Mapping[str, Any] | None = None
) -> dict[str, Any]

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() -> dict[str, Limit]

Limits set with :meth:set_limits (a small default set otherwise).

start_limits_poller

start_limits_poller(interval: float = 300.0) -> None

No-op (the fake never polls).

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 instance_url (StaticToken) or My Domain base_url sets :attr:instance_url; otherwise a default instance is used.

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

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

describe(*, cached: bool = True) -> dict[str, Any]

The describe set with fake.set_describe or a minimal synthesised one.

metadata

metadata() -> dict[str, Any]

Basic sObject info (objectDescribe + empty recentItems).

updated

updated(start: datetime, end: datetime) -> dict[str, Any]

Ids of records created or changed in [start, end].

deleted

deleted(start: datetime, end: datetime) -> dict[str, Any]

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.

upsert

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

Update the record whose field == value, or create it. :class:MultipleMatches on >1.

delete

delete(record_id: str) -> None

Delete a stored record (a second delete raises NotFound(ENTITY_IS_DELETED)).

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.

describe async

describe(*, cached: bool = True) -> dict[str, Any]

See :meth:FakeSObject.describe.

metadata async

metadata() -> dict[str, Any]

See :meth:FakeSObject.metadata.

updated async

updated(start: datetime, end: datetime) -> dict[str, Any]

See :meth:FakeSObject.updated.

deleted async

deleted(start: datetime, end: datetime) -> dict[str, Any]

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.

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

See :meth:FakeSObject.upsert.

delete async

delete(record_id: str) -> None

See :meth:FakeSObject.delete.

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

retrieve

retrieve(
    sobject: str,
    ids: Iterable[str],
    fields: Sequence[str],
    *,
    concurrency: int | None = None,
) -> list[dict[str, Any] | None]

Records in input order, None for unknown ids.

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.

retrieve async

retrieve(
    sobject: str,
    ids: Iterable[str],
    fields: Sequence[str],
    *,
    concurrency: int | None = None,
) -> list[dict[str, Any] | None]

See :meth:FakeCollections.retrieve.

FakeFiles

FakeFiles(state: FakeState, who: Who)

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

download(
    content_version_id: str,
) -> Iterator[FakeFileStream]

Yield a stream over the stored bytes of a ContentVersion.

download_bytes

download_bytes(content_version_id: str) -> bytes

The stored bytes of a ContentVersion.

download_attachment

download_attachment(attachment_id: str) -> bytes

The Body of an Attachment seeded with fake.add("Attachment", {"Body": b"..."}).

link(
    content_document_id: str,
    record_id: str,
    *,
    share_type: ShareType = "V",
    visibility: Visibility | None = None,
) -> str

Store a ContentDocumentLink. Returns its id.

list_for

list_for(record_id: str) -> list[FileLink]

The stored links of a record, as :class:FileLink values.

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

download_bytes(content_version_id: str) -> bytes

See :meth:FakeFiles.download_bytes.

download_attachment async

download_attachment(attachment_id: str) -> bytes

See :meth:FakeFiles.download_attachment.

link(
    content_document_id: str,
    record_id: str,
    *,
    share_type: ShareType = "V",
    visibility: Visibility | None = None,
) -> str

See :meth:FakeFiles.link.

list_for async

list_for(record_id: str) -> list[FileLink]

See :meth:FakeFiles.list_for.

FakeComposite

FakeComposite(state: FakeState, who: Who)

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

builder(
    *,
    all_or_none: bool = False,
    collate_subrequests: bool = False,
) -> FakeCompositeBuilder

See sf.composite.builder().

graph

graph() -> FakeGraphBuilder

See sf.composite.graph().

batch

batch(*, halt_on_error: bool = False) -> FakeBatchBuilder

See sf.composite.batch().

tree

tree(
    sobject: str, records: Iterable[Mapping[str, Any]]
) -> dict[str, str]

Create the record trees in one transaction; {referenceId: id}.

AsyncFakeComposite

AsyncFakeComposite(inner: FakeComposite)

Async fake of sf.composite; see :class:FakeComposite.

builder

builder(
    *,
    all_or_none: bool = False,
    collate_subrequests: bool = False,
) -> AsyncFakeCompositeBuilder

See sf.composite.builder().

graph

graph() -> AsyncFakeGraphBuilder

See sf.composite.graph().

batch

batch(
    *, halt_on_error: bool = False
) -> AsyncFakeBatchBuilder

See sf.composite.batch().

tree async

tree(
    sobject: str, records: Iterable[Mapping[str, Any]]
) -> dict[str, str]

See :meth:FakeComposite.tree.

FakeBulk

FakeBulk(state: FakeState, who: Who)

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

start_query(
    soql: str, *values: Any, include_deleted: bool = False
) -> FakeQueryJob

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

ingest_job(job_ids: Sequence[str]) -> FakeIngestJob

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.

expand_compound_fields

expand_compound_fields(
    sobject: str, fields: Sequence[str]
) -> list[str]

Expand compound fields with the describe set by fake.set_describe.

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

start_query(
    soql: str, *values: Any, include_deleted: bool = False
) -> AsyncFakeQueryJob

See :meth:FakeBulk.start_query.

query_job async

query_job(job_id: str) -> AsyncFakeQueryJob

See :meth:FakeBulk.query_job.

ingest_job async

ingest_job(job_ids: Sequence[str]) -> AsyncFakeIngestJob

See :meth:FakeBulk.ingest_job.

query async

query(
    soql: str,
    *values: Any,
    include_deleted: bool = False,
    parallel_downloads: int = 1,
    poll: Backoff | None = None,
    timeout: float = 3600.0,
) -> AsyncIterator[dict[str, str | None]]

See :meth:FakeBulk.query.

expand_compound_fields async

expand_compound_fields(
    sobject: str, fields: Sequence[str]
) -> list[str]

See :meth:FakeBulk.expand_compound_fields.

FakeUi

FakeUi(state: FakeState, who: Who)

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_info(
    name: str, *, cached: bool = True
) -> dict[str, Any]

Object metadata built from the describe.

picklist_values

picklist_values(
    name: str, record_type_id: str, *, cached: bool = True
) -> dict[str, Any]

The active picklistValues of each picklist field in the describe.

create_defaults

create_defaults(
    name: str, record_type_id: str | None = None
) -> dict[str, Any]

Default values (each describe field's defaultValue) for a new record.

clone_defaults

clone_defaults(record_id: str) -> dict[str, Any]

The stored record's values without its id and system fields.

list_views

list_views(name: str) -> dict[str, Any]

The list views set with fake.set_list_view.

list_records

list_records(
    name: str,
    list_view: str,
    *,
    page_size: int | None = None,
    page_token: str | None = None,
) -> dict[str, Any]

One page of the records a list view selects (__Recent: every record of the object).

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

object_info(
    name: str, *, cached: bool = True
) -> dict[str, Any]

See :meth:FakeUi.object_info.

picklist_values async

picklist_values(
    name: str, record_type_id: str, *, cached: bool = True
) -> dict[str, Any]

See :meth:FakeUi.picklist_values.

create_defaults async

create_defaults(
    name: str, record_type_id: str | None = None
) -> dict[str, Any]

See :meth:FakeUi.create_defaults.

clone_defaults async

clone_defaults(record_id: str) -> dict[str, Any]

See :meth:FakeUi.clone_defaults.

list_views async

list_views(name: str) -> dict[str, Any]

See :meth:FakeUi.list_views.

list_records async

list_records(
    name: str,
    list_view: str,
    *,
    page_size: int | None = None,
    page_token: str | None = None,
) -> dict[str, Any]

See :meth:FakeUi.list_records.

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

key_prefix(sobject: str) -> str

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.update", "query").

sobject str | None

sObject type involved, if any.

args Mapping[str, Any]

The call's arguments by name.

caller str | None

Caller tag (from tagged() or esf.call_context).

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 /services/data/vXX.X/ when versioned).

params Mapping[str, Any]

Query parameters.

json Any

Decoded JSON body, if json= was passed.

content bytes | None

Raw body, if content= was passed.

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

totalSize to report (defaults to the number of rows).

times int | None

How many times the script may match (None = unlimited).

kind str

"query" or "search".

hits int

How many times it matched so far.

matches

matches(text: str) -> bool

Whether this script answers text.

describe

describe() -> str

Short human description, for error messages.

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 example.my.salesforce.com.

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 httpx.Client(transport=...) or httpx.AsyncClient.

replay

replay(
    path: str | Path,
    *,
    match_query: bool = True,
    repeat: bool = False,
) -> MockTransport

An httpx.MockTransport serving the interactions recorded in path.

Parameters:

Name Type Description Default
path str | Path

Fixture written by :func:record (or by hand; see the module docstring).

required
match_query bool

Require the query string to match too (default). SOQL/SOSL in q and explain is compared with literals replaced by ?. False matches on method and path only, serving recordings in order.

True
repeat bool

When all matching interactions were used, serve the last one again instead of raising :class:ReplayMismatch.

False

Returns:

Type Description
MockTransport

A transport usable with both httpx.Client and httpx.AsyncClient. Its

MockTransport

handler.remaining attribute counts interactions not served yet.

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 httpx.HTTPTransport() (sync) or httpx.AsyncHTTPTransport() (async), created on first use.

None
redactor Redactor | None

Redaction settings.

None

handle_request

handle_request(request: Request) -> Response

Forward (sync), record, and return the response.

handle_async_request async

handle_async_request(request: Request) -> Response

Forward (async), record, and return the response.

close

close() -> None

Close the wrapped sync transport.

aclose async

aclose() -> None

Close the wrapped async transport.

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 *Phone* / *Fax* fields.

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()

text

text(value: str) -> str

Redact one string.

value

value(
    obj: Any,
    key: str | None = None,
    *,
    in_record: bool = False,
) -> Any

Redact a decoded JSON value recursively.

in_record marks the fields of an sObject record (a JSON object with attributes).

pairs

pairs(pairs: list[tuple[str, str]]) -> list[list[str]]

Redact decoded query/form pairs (SOQL/SOSL literals in q/explain too).

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.

store

store(make_store: Callable[[], TokenStore]) -> TokenStore

A fresh store from make_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

Override: return a zero-argument callable creating a fresh, empty store.

test_load_missing_returns_none

test_load_missing_returns_none(
    make_store: Callable[[], Any],
) -> None

Loading an unknown key returns None.

test_round_trip

test_round_trip(make_store: Callable[[], Any]) -> None

What is saved is what is loaded (all fields).

test_versions_increase

test_versions_increase(
    make_store: Callable[[], Any],
) -> None

Each save returns a strictly greater version.

test_cas_conflict

test_cas_conflict(make_store: Callable[[], Any]) -> None

A stale expected_version raises TokenConflict and changes nothing.

test_cas_on_missing_key_conflicts

test_cas_on_missing_key_conflicts(
    make_store: Callable[[], Any],
) -> None

Expecting a version for a key that has none raises TokenConflict.

test_delete_removes_both_tokens

test_delete_removes_both_tokens(
    make_store: Callable[[], Any],
) -> 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(
    make_store: Callable[[], Any],
) -> 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(
    make_store: Callable[[], Any],
) -> None

Writes to one key never affect another.

test_lock_is_usable

test_lock_is_usable(make_store: Callable[[], Any]) -> None

lock(key), when implemented, is an async context manager.

test_lock_excludes_a_second_holder

test_lock_excludes_a_second_holder(
    make_store: Callable[[], Any],
) -> None

While one task holds lock(key), another cannot enter it.

test_concurrent_cas_has_one_winner

test_concurrent_cas_has_one_winner(
    make_store: Callable[[], Any],
) -> None

N tasks CAS-saving against the same version: exactly one wins.

FakePubSub

FakePubSub(state: FakeState, who: Who)

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

"/event/Order_Event__e" or a change event channel.

required
payload Mapping[str, Any]

The decoded event fields.

required
event_id str | None

The event's id (EventUuid). Defaults to a random UUID, on change event channels too, as Salesforce sends.

None
schema_id str

Reported as :attr:PubSubEvent.schema_id.

_SCHEMA_ID
change ChangeHeader | None

The decoded header of a change event; prefer :meth:emit_change.

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. "Account".

required
change_type ChangeType | str

"CREATE", "UPDATE", ..., "GAP_UPDATE", "GAP_OVERFLOW".

required
record_ids Iterable[str]

The changed records (empty for GAP_OVERFLOW).

()
changed_fields Iterable[str]

Field names, Parent.Child for compound components.

()
nulled_fields Iterable[str]

Fields set to null.

()
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. /data/AccountChangeEvent. Pass "/data/ChangeEvents" to emit on the standard channel.

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

emitted

emitted(topic: str) -> list[PubSubEvent]

Every event emitted on topic so far.

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.

store

store(make_store: Callable[[], ReplayStore]) -> ReplayStore

A fresh store from make_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

Override: return a zero-argument callable creating a fresh, empty store.

test_load_missing_returns_none

test_load_missing_returns_none(
    make_store: Callable[[], Any],
) -> None

An unknown key loads None.

test_round_trip

test_round_trip(make_store: Callable[[], Any]) -> None

What is saved is loaded byte for byte, as bytes.

test_save_overwrites

test_save_overwrites(make_store: Callable[[], Any]) -> None

A later save replaces the earlier position.

test_keys_are_independent

test_keys_are_independent(
    make_store: Callable[[], Any],
) -> None

Orgs and topics never share a position.

test_positions_persist_across_instances

test_positions_persist_across_instances(
    make_store: Callable[[], Any],
) -> 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(
    make_store: Callable[[], Any],
) -> None

Concurrent saves (one subscription each) all land.

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: factory esf_replay(path, **kwargs) -> httpx.MockTransport; relative paths resolve against the requesting test file's directory.
  • esf_sandbox_auth: an Auth built from ESF_SANDBOX_* variables (skips if unset).

Marker:

  • @pytest.mark.esf_sandbox: real-org test, skipped unless ESF_SANDBOX_ACCESS_TOKEN + ESF_SANDBOX_INSTANCE_URL, or ESF_SANDBOX_DOMAIN + ESF_SANDBOX_CLIENT_ID + ESF_SANDBOX_CLIENT_SECRET (or ESF_SANDBOX_USERNAME + ESF_SANDBOX_PRIVATE_KEY_FILE) are set.

Importing this module needs only pytest (respx is not required).