Install AI Tools

B2C Commerce tools, documentation, and skills for your assistant.

Claude

Install the plugin Recommended

bash
claude plugin marketplace add SalesforceCommerceCloud/b2c-developer-tooling
claude plugin install b2c-dx-mcp@b2c-developer-tooling

Start a new Claude Code session. To install for the current project only, run it from your project directory with --scope project.

Manual MCP setup
bash
claude mcp add --transport stdio --scope user b2c-dx-mcp -- npx -y @salesforce/b2c-dx-mcp@latest

Start a new session. To configure the current project only, run it from your project directory with --scope project. See Claude Code MCP setup.

Claude Desktop setup

Codex

Install the plugin Recommended

bash
codex plugin marketplace add SalesforceCommerceCloud/b2c-developer-tooling
codex plugin add b2c-dx-mcp@b2c-developer-tooling

Start a new Codex session in your project. This setup also works with the Codex IDE extension and the ChatGPT Work desktop app.

Manual MCP setup
bash
codex mcp add b2c-dx-mcp -- npx -y @salesforce/b2c-dx-mcp@latest

Or add this to ~/.codex/config.toml (or $CODEX_HOME/config.toml if customized):

toml
[mcp_servers.b2c-dx-mcp]
command = "npx"
args = ["-y", "@salesforce/b2c-dx-mcp@latest"]

Start a new session. See Codex MCP configuration.

ChatGPT online setup

VS Code

Install the plugin Recommended

  1. Open the Command Palette (Cmd/Ctrl+Shift+P) and run Chat: Install Plugin from Source.
  2. Enter SalesforceCommerceCloud/b2c-developer-tooling.
  3. Select b2c-dx-mcp and follow the installation prompts.
  4. Start a new chat in GitHub Copilot.
Manual MCP setup

Add this to .vscode/mcp.json in your workspace:

json
{
  "servers": {
    "b2c-dx-mcp": {
      "type": "stdio",
      "command": "npx",
      "args": ["-y", "@salesforce/b2c-dx-mcp@latest"]
    }
  }
}

See VS Code MCP setup.

Copilot CLI setup

Cursor

Reload the MCP server in Cursor after installation.

Manual MCP setup

Add this to .cursor/mcp.json in your project:

json
{
  "mcpServers": {
    "b2c-dx-mcp": {
      "command": "npx",
      "args": ["-y", "@salesforce/b2c-dx-mcp@latest"]
    }
  }
}

For all projects, use ~/.cursor/mcp.json instead.

See Cursor's MCP documentation.

OpenCode

Add this to opencode.json in your project:

json
{
  "mcp": {
    "b2c-dx-mcp": {
      "type": "local",
      "command": ["npx", "-y", "@salesforce/b2c-dx-mcp@latest"],
      "enabled": true
    }
  }
}

Restart OpenCode. For all projects, use ~/.config/opencode/opencode.json. See OpenCode MCP setup.

Gemini

Run:

bash
gemini mcp add --scope user b2c-dx-mcp -- npx -y @salesforce/b2c-dx-mcp@latest

Start a new Gemini CLI session. To configure the current project only, run it from your project directory with --scope project. See Gemini CLI MCP setup.

No separate skills plugins needed.

Other clients and manual setup →
Skip to content
View as Markdown
View as Markdown

b2c_tooling_sdk.clients ​

HTTP clients for B2C Commerce APIs.

Mirrors the clients subpath of the TypeScript SDK. Provides the core HttpClient (openapi-fetch analog with ClientResult), the shared middleware chain, the OCAPI and WebDAV clients, the SCAPI/OCAPI dual-backend utilities, the typed domain clients (SLAS, ODS, MRT, Account Manager, SCAPI Jobs/ Sites/Catalogs/Scripts/Merchant-Users/Merchant-Roles/Schemas, Custom APIs, CDN Zones, Preferences, Metrics, Granular Replications), the middleware registry, TLS/mTLS transport helpers, and API error-message utilities.

Importing this package auto-registers the User-Agent middleware providers (see b2c_tooling_sdk.clients.user_agent).

Classes ​

AccountManagerClient ​

python
class AccountManagerClient

Unified Account Manager API client that combines users, roles, API clients, and organizations.

Provides direct access to every Account Manager API operation through a single interface, while internally using separate configured clients for each domain. Role and org mappings (id/enum-name and id/name) are lazily fetched and cached.

get_user method ​

python
async def get_user(user_id: str, expand: list[UserExpandOption] | None = None) -> AccountManagerUser

Get user by ID.

list_users method ​

python
async def list_users(options: ListUsersOptions | None = None) -> UserCollection

List users with pagination.

create_user method ​

python
async def create_user(user: UserCreate) -> AccountManagerUser

Create a new user.

update_user method ​

python
async def update_user(user_id: str, changes: UserUpdate) -> AccountManagerUser

Update an existing user.

delete_user method ​

python
async def delete_user(user_id: str) -> None

Disable a user (soft delete).

purge_user method ​

python
async def purge_user(user_id: str) -> None

Purge a user (hard delete).

reset_user method ​

python
async def reset_user(user_id: str) -> None

Reset a user to INITIAL state.

find_user_by_login method ​

python
async def find_user_by_login(login: str, expand: list[UserExpandOption] | None = None) -> AccountManagerUser | None

Find a user by login (email).

grant_role method ​

python
async def grant_role(user_id: str, role: str, scope: str | None = None) -> AccountManagerUser

Grant a role to a user, optionally scoped to specific tenants.

revoke_role method ​

python
async def revoke_role(user_id: str, role: str, scope: str | None = None) -> AccountManagerUser

Revoke a role from a user, optionally removing only specific tenant scopes.

get_role method ​

python
async def get_role(role_id: str) -> AccountManagerRole

Get role by ID.

list_roles method ​

python
async def list_roles(options: ListRolesOptions | None = None) -> RoleCollection

List roles with pagination.

get_role_mapping method ​

python
async def get_role_mapping() -> RoleMapping

Get the role mapping (id <-> roleEnumName), lazily cached.

get_org_mapping method ​

python
async def get_org_mapping() -> OrgMapping

Get the org mapping (id -> name), lazily cached.

list_api_clients method ​

python
async def list_api_clients(options: ListApiClientsOptions | None = None) -> APIClientCollection

List API clients with pagination.

get_api_client method ​

python
async def get_api_client(api_client_id: str, expand: list[ApiClientExpandOption] | None = None) -> AccountManagerApiClient

Get API client by ID.

create_api_client method ​

python
async def create_api_client(body: APIClientCreate) -> AccountManagerApiClient

Create a new API client.

update_api_client method ​

python
async def update_api_client(api_client_id: str, body: APIClientUpdate) -> AccountManagerApiClient

Update an existing API client.

delete_api_client method ​

python
async def delete_api_client(api_client_id: str) -> None

Delete an API client (must be disabled 7+ days).

change_api_client_password method ​

python
async def change_api_client_password(api_client_id: str, old_password: str, new_password: str) -> None

Change an API client password.

get_org method ​

python
async def get_org(org_id: str) -> AccountManagerOrganization

Get organization by ID.

get_org_by_name method ​

python
async def get_org_by_name(name: str) -> AccountManagerOrganization

Get organization by name.

list_orgs method ​

python
async def list_orgs(options: ListOrgsOptions | None = None) -> OrganizationCollection

List organizations with pagination.

AccountManagerClientConfig ​

python
class AccountManagerClientConfig

Configuration for creating Account Manager clients (users, roles, apiclients, orgs).

Fields

NameTypeDefault
hostnamestr | NoneNone
middleware_registryMiddlewareRegistry | NoneNone

AccountManagerOrgsClient ​

python
class AccountManagerOrgsClient

Account Manager Organizations API client.

Hand-rolled request logic (mirrors the TS createAccountManagerOrgsClient): a private, non-retrying auth middleware plus registry/logging middleware, and status-code-driven error mapping instead of the ClientResult convention used by the other AM clients.

get_org method ​

python
async def get_org(org_id: str) -> AccountManagerOrganization

Get organization by ID.

get_org_by_name method ​

python
async def get_org_by_name(name: str) -> AccountManagerOrganization

Get organization by name (searches for exact or partial match).

list_orgs method ​

python
async def list_orgs(options: ListOrgsOptions | None = None) -> OrganizationCollection

List organizations with pagination.

BackendBase ​

python
class BackendBase(Protocol)

Common base for every SCAPI/OCAPI dual backend.

Mirrors the TypeScript BackendBase interface: a backend exposes a name identifying which transport it speaks so the fallback wrapper can report the currently-active backend.

Fields

NameTypeDescription
nameLiteral['ocapi', 'scapi']Which transport this backend speaks.

B2COrgInfo ​

python
class B2COrgInfo(BaseModel)

Fields

NameType
is_b2c_customerbool
instanceslist[Instance]

B2CTargetInfo ​

python
class B2CTargetInfo(BaseModel)

Fields

NameTypeDefault
instance_idstr
siteslist[Site] | NoneNone

BuildScapiClientOptions ​

python
class BuildScapiClientOptions

Domain-specific options for build_scapi_client.

Fields

NameTypeDefault
path_segmentstr
domain_keyHttpClientType
log_prefixstr
scope_cascadeScopeCascade | NoneNone
default_scopeslist[str] | NoneNone

CdnZonesClientConfig ​

python
class CdnZonesClientConfig

Configuration for creating a CDN Zones client.

Fields

NameTypeDefault
short_codestr
tenant_idstr
scopeslist[str] | NoneNone
middleware_registryMiddlewareRegistry | Nonefield(default=None)

CdnZonesClientOptions ​

python
class CdnZonesClientOptions

Options for creating a CDN Zones client.

Fields

NameTypeDefault
read_writeboolFalse

CdnZonesError ​

python
class CdnZonesError(BaseModel)

Fields

NameType
titlestr
typestr
detailstr
instancestr | None

ClientResult ​

python
class ClientResult

Result of a typed client call — mirrors openapi-fetch {data, error, response}.

Never raised: a successful (2xx) response populates data, any other status populates error, and response is always the raw httpx.Response. Only network failures raise (before a result exists).

Fields

NameTypeDefault
dataAnyNone
errorAnyNone
responsehttpx.Response | NoneNone

CodeVersion ​

python
class CodeVersion(BaseModel)

Fields

NameTypeDefault
idstr | NoneField(None, max_length=256, min_length=1)
activebool | NoneNone
cartridgeslist[Cartridge] | NoneNone
compatibilityModestr | NoneField(None, max_length=100)
activationTimeAwareDatetime | NoneNone
lastModificationTimeAwareDatetime | NoneNone
rollbackbool | NoneNone
totalSizeint | NoneNone
webDavUrlstr | NoneField(None, max_length=4000)

ContentAssetItemPrivate ​

python
class ContentAssetItemPrivate(BaseModel)

Details of the published content asset from a private library

Fields

NameType
contentIdstr
typeType
siteIdstr

ContentAssetItemShared ​

python
class ContentAssetItemShared(BaseModel)

Details of the published content asset from a shared library

Fields

NameType
contentIdstr
typeType1
libraryIdstr

CustomApisClientConfig ​

python
class CustomApisClientConfig

Configuration for creating a Custom APIs client.

Fields

NameTypeDefault
short_codestr
tenant_idstr
scopeslist[str] | NoneNone
middleware_registryMiddlewareRegistry | Nonefield(default=None)

CustomPreference ​

python
class CustomPreference(BaseModel)

Preference object

Fields

NameTypeDefault
groupIdstrField(..., description='The ID of the preference group.')
idstrField(..., description='The Preference Id.')
valueAnyField(..., description='The value for the Preference Id.')

CustomPreferenceList ​

python
class CustomPreferenceList(PaginatedResultBase)

Document representing a Custom Preference result.

Fields

NameType
datalist[CustomPreference]
limitint
offsetint
totalint

DualBackendConfig ​

python
class DualBackendConfig

Common input shape of every dual-backend factory.

SCAPI coordinates and the scope-flexible auth strategy are sourced from the instance via B2CInstance.scapi_client_config. A backend is "SCAPI-capable" iff that getter returns a value. preference is optional: when None it falls back to the instance's own B2CInstance.api_backend (default "auto").

Fields

NameTypeDefault
instanceB2CInstance
preferenceApiBackendPreference | NoneNone

DualBackendCtors ​

python
class DualBackendCtors(Generic[T])

Constructors needed to build a dual-backend instance.

Each domain plugs in its own SCAPI/OCAPI backend factories; the generic factory wires them together. scapi receives a ScapiBackendCtorConfig; ocapi receives the B2CInstance directly.

Fields

NameType
domain_namestr
scapiCallable[[ScapiBackendCtorConfig], T]
ocapiCallable[[B2CInstance], T]

ExecutionStatus ​

python
class ExecutionStatus(Enum)

ExitStatus ​

python
class ExitStatus(BaseModel)

Fields

NameTypeDefault
codestr | NoneField(None, max_length=256)
messagestr | NoneField(None, max_length=4000)
statusStatus | NoneNone

GranularReplicationsClientConfig ​

python
class GranularReplicationsClientConfig

Configuration for creating a Granular Replications API client.

Parameters

NameTypeDescription
short_codestrThe instance short code (e.g. kv7kzm78).
tenant_idstrThe tenant ID (e.g. zzxy_prd).
scopeslist[str] | NoneOptional custom OAuth scopes. Defaults to sfcc.granular-replications.rw and the tenant-specific scope.
middleware_registryMiddlewareRegistry | NoneOptional custom middleware registry for request/response interceptors.

Fields

NameTypeDefault
short_codestr
tenant_idstr
scopeslist[str] | NoneNone
middleware_registryMiddlewareRegistry | Nonefield(default=None)

GranularReplicationsError ​

python
class GranularReplicationsError(BaseModel)

Standard error response following RFC 7807

Fields

NameType
typestr
titlestr
detailstr | None
instancestr | None

HttpClient ​

python
class HttpClient

Async HTTP client with a middleware chain, returning ClientResult.

Parameters

NameTypeDescription
base_urlstrBase URL prefix (e.g. https://host/s/-/dw/data/v25_6).
middlewarelist[Middleware] | NoneMiddleware in registration order (auth first, logging last).
client_typestrThe HttpClientType label passed to middleware contexts.
transporthttpx.AsyncBaseTransport | NoneOptional TLS/mTLS transport (mirrors the undici dispatcher).

Fields

NameTypeDefault
middlewarelist[Middleware]list(middleware or [])

use method ​

python
def use(middleware: Middleware) -> None

Append a middleware to the chain (mirrors openapi-fetch client.use).

aclose method ​

python
async def aclose() -> None

Close the underlying HTTP client and release its connections.

request method ​

python
async def request(method: str, path: str, *, params: dict[str, Any] | None = None, body: Any = None, headers: dict[str, str] | None = None) -> ClientResult

Perform a request through the middleware chain and return a ClientResult.

Parameters

NameTypeDescription
methodstrHTTP method (GET, POST, ...).
pathstrPath appended to base_url; may contain {name} placeholders.
paramsdict[str, Any] | NoneOptional {"path": {...}, "query": {...}} parameters.
bodyAnyOptional request body (dict/list → JSON, or raw bytes/str).
headersdict[str, str] | NoneOptional extra request headers.

Raises

  • NetworkError — on transport-level failures (never on 4xx/5xx).

get method ​

python
async def get(path: str, options: dict[str, Any] | None = None) -> ClientResult

Perform a GET request. options may carry params/headers.

post method ​

python
async def post(path: str, options: dict[str, Any] | None = None) -> ClientResult

Perform a POST request. options may carry params/body/headers.

put method ​

python
async def put(path: str, options: dict[str, Any] | None = None) -> ClientResult

Perform a PUT request. options may carry params/body/headers.

patch method ​

python
async def patch(path: str, options: dict[str, Any] | None = None) -> ClientResult

Perform a PATCH request. options may carry params/body/headers.

delete method ​

python
async def delete(path: str, options: dict[str, Any] | None = None) -> ClientResult

Perform a DELETE request. options may carry params/headers.

HttpMiddlewareProvider ​

python
class HttpMiddlewareProvider(Protocol)

Supplies middleware for HTTP clients.

Providers can return different middleware per client type, or None to skip a client type.

Fields

NameType
namestr

get_middleware method ​

python
def get_middleware(client_type: HttpClientType) -> UnifiedMiddleware | None

Return middleware for client_type, or None to skip it.

JobExecution ​

python
class JobExecution(BaseModel)

Fields

NameTypeDefault
idstrField(..., max_length=256, min_length=1)
jobIdstrField(..., max_length=256, min_length=1)
jobDescriptionstr | NoneField(None, max_length=4000)
clientIdstr | NoneField(None, max_length=256)
userLoginstr | NoneField(None, max_length=256)
executionStatusExecutionStatus | NoneNone
statusstrField(..., max_length=256)
startTimeAwareDatetime | NoneNone
endTimeAwareDatetime | NoneNone
creationDateAwareDatetime | NoneNone
durationint | NoneNone
effectiveDurationint | NoneNone
modificationTimeAwareDatetime | NoneNone
lastModifiedAwareDatetime | NoneNone
executedServerIdstr | NoneField(None, max_length=256)
exitStatusExitStatus | NoneNone
statusMetadataStatusMetadata | NoneNone
isLogFileExistingbool | NoneNone
isRestartbool | NoneNone
logFilePathstr | NoneField(None, max_length=4000)
parameterslist[Parameter] | NoneNone
executionScopeslist[ExecutionScope] | NoneNone
retryInformationJobExecutionRetryInformation | NoneNone
continueInformationJobExecutionContinueInformation | NoneNone
stepExecutionslist[StepExecution] | NoneNone

JobExecutionSearchResult ​

python
class JobExecutionSearchResult(PaginatedSearchResult)

Fields

NameType
hitslist[Hit]
queryQuery

JobParameter ​

python
class JobParameter(BaseModel)

Fields

NameType
namestr
valuestr

JobStepExecution ​

python
class JobStepExecution(BaseModel)

Fields

NameTypeDefault
idstr | NoneField(None, max_length=256, min_length=1)
stepIdstr | NoneField(None, max_length=256, min_length=1)
stepDescriptionstr | NoneField(None, max_length=4000)
stepTypeIdstr | NoneField(None, max_length=256)
stepTypeInfostr | NoneField(None, max_length=4000)
executionScopestr | NoneField(None, max_length=256)
executionStatusExecutionStatus | NoneNone
statusstr | NoneField(None, max_length=256)
startTimeAwareDatetime | NoneNone
endTimeAwareDatetime | NoneNone
durationint | NoneNone
modificationTimeAwareDatetime | NoneNone
statusMetadataStatusMetadata | NoneNone
exitStatusExitStatus | NoneNone
includeStepsFromJobIdstr | NoneField(None, max_length=256)
isChunkOrientedbool | NoneNone
chunkSizeint | NoneNone
itemFilterCountint | NoneNone
itemWriteCountint | NoneNone
totalItemCountint | NoneNone

ListApiClientsOptions ​

python
class ListApiClientsOptions

Options for listing API clients.

Fields

NameTypeDefault
sizeint | NoneNone
pageint | NoneNone

ListOrgsOptions ​

python
class ListOrgsOptions

Options for listing organizations.

Fields

NameTypeDefault
sizeint | NoneNone
pageint | NoneNone
allboolFalse

ListRolesOptions ​

python
class ListRolesOptions

Options for listing roles.

Fields

NameTypeDefault
sizeint | NoneNone
pageint | NoneNone
role_target_typeLiteral['ApiClient', 'User'] | NoneNone

ListUsersOptions ​

python
class ListUsersOptions

Options for listing users.

Fields

NameTypeDefault
sizeint | NoneNone
pageint | NoneNone

Metric ​

python
class Metric(BaseModel)

Fields

NameTypeDefault
metricIdstr
titlestrField(..., max_length=200, min_length=1)
descriptionstrField(..., max_length=500, min_length=1)
unitstr | NoneField(None, max_length=50, min_length=0)
dataSerieslist[DataSeries]

MetricDataPoint ​

python
class MetricDataPoint(BaseModel)

Fields

NameTypeDefault
timestampintField(..., ge=0)
valuefloat

MetricDataSeries ​

python
class MetricDataSeries(BaseModel)

Fields

NameTypeDefault
idstrField(..., max_length=200, min_length=1)
namestrField(..., max_length=200, min_length=1)
datalist[DataPoint]

MetricsClientConfig ​

python
class MetricsClientConfig

Configuration for creating a Metrics API client.

Fields

NameTypeDefault
short_codestr
tenant_idstr
scopeslist[str] | NoneNone
middleware_registryMiddlewareRegistry | Nonefield(default=None)

MetricsDataResponse ​

python
class MetricsDataResponse(BaseModel)

Fields

NameType
datalist[Metric]

MetricsError ​

python
class MetricsError(BaseModel)

Fields

NameTypeDefault
titlestrField(..., max_length=256)
typestrField(..., max_length=2048)
detailstr
instancestr | NoneField(None, max_length=2048)

Middleware ​

python
class Middleware(Protocol)

Middleware for HttpClient (analogous to an openapi-fetch middleware).

Both hooks are optional. on_request may mutate ctx.request in place and/or return a replacement request; on_response may return a replacement response (e.g. a retry result). Returning None keeps the current object.

on_request method ​

python
async def on_request(ctx: MiddlewareRequestContext) -> httpx.Request | None

Called before the request is sent; may mutate or replace it.

on_response method ​

python
async def on_response(ctx: MiddlewareResponseContext) -> httpx.Response | None

Called after the response is received; may mutate or replace it.

MiddlewareRegistry ​

python
class MiddlewareRegistry

Registry for HTTP middleware providers.

Collects middleware from registered providers and returns it in registration order when requested by a client factory.

Fields

NameTypeDescription
sizeintNumber of registered providers.

register method ​

python
def register(provider: HttpMiddlewareProvider) -> None

Register a middleware provider (called in registration order).

unregister method ​

python
def unregister(name: str) -> bool

Remove a provider by name; return True if one was removed.

get_middleware method ​

python
def get_middleware(client_type: HttpClientType) -> list[UnifiedMiddleware]

Collect middleware from all providers for client_type, in order.

clear method ​

python
def clear() -> None

Clear all registered providers (primarily for testing).

get_provider_names method ​

python
def get_provider_names() -> list[str]

Return the names of all registered providers.

MiddlewareRequestContext ​

python
class MiddlewareRequestContext

Context passed to a middleware's on_request hook.

Fields

NameTypeDefault
requesthttpx.Request
client_typestr
schema_pathstr''
fetchFetchFn | NoneNone

MiddlewareResponseContext ​

python
class MiddlewareResponseContext

Context passed to a middleware's on_response hook.

Fields

NameTypeDefault
requesthttpx.Request
responsehttpx.Response
client_typestr
schema_pathstr''
fetchFetchFn | NoneNone

MrtB2CClientConfig ​

python
class MrtB2CClientConfig

Configuration for creating an MRT B2C client.

Fields

NameTypeDefault
originstr | NoneNone
middleware_registryMiddlewareRegistry | Nonefield(default=None)

MrtClientConfig ​

python
class MrtClientConfig

Configuration for creating an MRT client.

Fields

NameTypeDefault
originstr | NoneNone
middleware_registryMiddlewareRegistry | Nonefield(default=None)

OcapiDeprecatedError ​

python
class OcapiDeprecatedError(Exception)

Raised when an OCAPI operation fails because OCAPI is deprecated.

Carries actionable SCAPI-setup guidance — including the exact scope the failed operation needs, when supplied — so callers surface a helpful message instead of an opaque "Failed to ..." line. The original error is attached as __cause__ (via raise ... from) at the throw site.

OdsClientConfig ​

python
class OdsClientConfig

Configuration for creating an ODS client.

Fields

NameTypeDefault
hoststr | NoneNone
extra_paramsdict[str, Any] | NoneNone
middleware_registryMiddlewareRegistry | Nonefield(default=None)

OpenApiSchema ​

python
class OpenApiSchema(BaseModel)

An OpenAPI 3.0 schema specification

Fields

NameTypeDefault
openapistr | None
infoInfo | NoneNone
pathsdict[str, Any] | NoneNone
componentsdict[str, Any] | NoneNone

OrgMapping ​

python
class OrgMapping

Organization mapping built from the Account Manager organizations API. Maps org ID to name.

Fields

NameType
by_iddict[str, str]

OrganizationPreferences ​

python
class OrganizationPreferences(BaseModel)

Represents custom preferences at the global (organization) level within a preference group. Custom preference attributes are returned with the "c_" prefix.

Fields

NameType
sitePreferenceslist[SitePreferences] | None

PatchedB2CTargetInfo ​

python
class PatchedB2CTargetInfo(BaseModel)

Fields

NameTypeDefault
instance_idstr | None
siteslist[Site] | NoneNone

PreferenceValue ​

python
class PreferenceValue(BaseModel)

Represents a single preference value with its attribute definition and site-specific values.

Fields

NameTypeDefault
idstr
descriptiondict[str, Description3] | NoneNone
displayNamedict[str, DisplayName2] | NoneNone
attributeDefinitionObjectAttributeDefinition | NoneNone
siteValuesdict[str, Any] | None
valueTypeValueType | NoneNone

PreferenceValueSearchResult ​

python
class PreferenceValueSearchResult(PaginatedSearchResult)

Document representing a preference value search result.

Fields

NameType
hitslist[PreferenceValue] | None

PreferencesClientConfig ​

python
class PreferencesClientConfig

Configuration for creating a Preferences client.

Fields

NameTypeDefault
short_codestr
tenant_idstr
scopeslist[str] | NoneNone
middleware_registryMiddlewareRegistry | Nonefield(default=None)

PreferencesClientOptions ​

python
class PreferencesClientOptions

Options for creating a Preferences client.

Fields

NameTypeDefault
read_writeboolFalse

PreferencesError ​

python
class PreferencesError(BaseModel)

Fields

NameType
titlestr
typestr
detailstr
instancestr | None

PreferencesSearchRequest ​

python
class PreferencesSearchRequest(BaseModel)

Document representing a search request for retrieving items within the Data API. The query is a potentially complex set of expressions. The fields and expands that each query supports are defined within the search resource.

Fields

NameType
limitint | None
queryQuery
sortslist[Sort] | None
offsetint | None

PriceTableItem ​

python
class PriceTableItem(BaseModel)

Details of the published price table (only available if a price table was published)

Fields

NameType
priceTableIdstr

ProductItem ​

python
class ProductItem(BaseModel)

Details of the published product (only available if a product was published)

Fields

NameType
productIdstr

PropfindEntry ​

python
class PropfindEntry

A single entry returned by a PROPFIND (directory listing).

Fields

NameTypeDefault
hrefstr
is_collectionbool
display_namestr | NoneNone
content_lengthint | NoneNone
last_modifieddatetime | NoneNone
content_typestr | NoneNone

PublishIdResponse ​

python
class PublishIdResponse(BaseModel)

Item successfully queued for publishing

Fields

NameType
idstr

PublishProcessListResponse ​

python
class PublishProcessListResponse(ResultBase)

Paginated list of publish processes

Fields

NameType
datalist[PublishProcessResponse]
offsetint

PublishProcessResponse ​

python
class PublishProcessResponse(BaseModel)

Publish process details

Fields

NameTypeDefault
idstr
statusStatus
startTimeAwareDatetime
endTimeAwareDatetime | None
initiatedBystr
productItemProductItem | NoneNone
priceTableItemPriceTableItem | NoneNone
contentAssetItemContentAssetItemPrivate | ContentAssetItemShared | NoneNone

ResolveBackendOptions ​

python
class ResolveBackendOptions

Inputs to resolve_scapi_or_ocapi.

Fields

NameType
preferenceApiBackendPreference
has_scapi_configbool
domain_namestr

Role ​

python
class Role(RootModel[str])

Fields

NameTypeDefault
rootstrField(..., max_length=256)

RoleMapping ​

python
class RoleMapping

Role mapping built from the Account Manager roles API.

Maps between role id (e.g. bm-admin) and roleEnumName (e.g. ECOM_ADMIN).

Fields

NameType
by_iddict[str, str]
by_enum_namedict[str, str]
descriptionsdict[str, str]

RolePermissions ​

python
class RolePermissions(BaseModel)

Fields

NameTypeDefault
moduleRoleModulePermissions | NoneNone
functionalRoleFunctionalPermissions | NoneNone
localeRoleLocalePermissions | NoneNone
webdavRoleWebdavPermissions | NoneNone

RoleSearch ​

python
class RoleSearch(PaginatedResultBase)

Fields

NameType
datalist[Datum]

ScapiBackendCtorConfig ​

python
class ScapiBackendCtorConfig

Configuration passed to a SCAPI backend constructor.

Domains may read additional data off instance (log/WebDAV access) but always receive short_code + tenant_id + auth.

Fields

NameType
short_codestr
tenant_idstr
authAuthStrategy
instanceB2CInstance

ScapiCapabilityUnsupportedError ​

python
class ScapiCapabilityUnsupportedError(Exception)

Raised when a requested operation cannot be expressed on SCAPI.

For example, toggling the disabled flag via the SCAPI Users PATCH, which the SCAPI schema does not include. The fallback wrapper recognizes this and falls back to OCAPI; in explicit scapi mode it propagates so the caller sees the limitation.

ScapiCatalog ​

python
class ScapiCatalog(BaseModel)

Fields

NameTypeDefault
idstr
namedict[str, str] | NoneNone
descriptiondict[str, str] | NoneNone
onlinebool | NoneNone

ScapiCatalogs ​

python
class ScapiCatalogs(BaseModel)

Fields

NameType
datalist[Catalog]
limitint
offsetint
totalint

ScapiClientConfig ​

python
class ScapiClientConfig

Caller-supplied SCAPI coordinates and overrides.

Fields

NameTypeDefault
short_codestr
tenant_idstr
scopeslist[str] | NoneNone
middleware_registryMiddlewareRegistry | Nonefield(default=None)

ScapiRequestError ​

python
class ScapiRequestError(Exception)

A structured SCAPI response failure.

Backends must retain the response status so the shared fallback policy can distinguish a definite rejection from an ambiguous transport/server failure.

ScapiSchemasClientConfig ​

python
class ScapiSchemasClientConfig

Configuration for creating a SCAPI Schemas client.

Fields

NameTypeDefault
short_codestr
tenant_idstr
scopeslist[str] | NoneNone
middleware_registryMiddlewareRegistry | Nonefield(default=None)

ScapiSchemasError ​

python
class ScapiSchemasError(BaseModel)

Fields

NameType
titlestr
typestr
detailstr
instancestr | None

ScapiSite ​

python
class ScapiSite(BaseModel)

Fields

NameTypeDefault
idstrField(..., max_length=32, min_length=1)
displayNamedict[str, DisplayName] | NoneNone
descriptiondict[str, Description] | NoneNone
customerListLinkCustomerListLink | NoneNone
inDeletionbool | NoneNone
storefrontStatusStorefrontStatus | NoneNone
siteCatalogIdstr | NoneField(None, max_length=256, min_length=1)
cartridgesstr | NoneField(None, max_length=4000)
customCartridgesstr | NoneField(None, max_length=4000)
creationDateAwareDatetime | NoneNone
lastModifiedAwareDatetime | NoneNone

ScapiSiteSearchResult ​

python
class ScapiSiteSearchResult(PaginatedSearchResult)

Fields

NameType
hitslist[Hit]
queryQuery

ScapiSites ​

python
class ScapiSites(PaginatedResultBase)

Fields

NameType
datalist[Datum]

ScapiUserAuthUnsupportedError ​

python
class ScapiUserAuthUnsupportedError(Exception)

Raised when browser-based Account Manager user auth is passed to a SCAPI Admin client.

SchemaListItem ​

python
class SchemaListItem(BaseModel)

Fields

NameTypeDefault
schemaVersionstr | None
apiFamilystr | None
apiNamestr | None
apiVersionstr | None
statusSchemaStatus | NoneNone
linkstr | None

SchemaListResult ​

python
class SchemaListResult(ResultBase)

Fields

NameTypeDefault
filterSchemaListFilter | NoneNone
datalist[SchemaListItem] | NoneNone

ScopeCascade ​

python
class ScopeCascade

Scope cascade for a SCAPI domain.

The SCAPI auth middleware picks read or write based on the per-operation scope-mode hint and walks the chosen cascade through the auth strategy until one candidate survives at Account Manager. Each candidate is a list of scopes; the auth strategy adds any base (e.g. tenant) scopes itself.

Fields

NameType
readlist[list[str]]
writelist[list[str]]

ScopeTierManager ​

python
class ScopeTierManager(Generic[C])

Lazy-initialized manager for clients at different scope tiers.

  • First read or write call builds the rw client and caches it.
  • If the caller detects an invalid_scope error on a read attempt, it calls downgrade_to_read_only and the next read uses the read-only client.
  • Once downgraded, write requests raise — the API client lacks rw scope.

The same rw client serves both read and write while the rw scope is valid; a separate read-only client is only built after a downgrade.

Fields

NameTypeDescription
resolved_tierScopeTier | NoneThe currently-resolved tier, or None before first use.

get_client_for_write method ​

python
def get_client_for_write() -> C

Return a client suitable for write operations.

Raises

  • ScapiCapabilityUnsupportedError — if we've already downgraded to read-only — the API client doesn't have the rw scope. Raising this (rather than a plain error) lets the SCAPI/OCAPI fallback wrapper recognize the capability gap and route the write through OCAPI in auto mode.

get_client_for_read method ​

python
def get_client_for_read() -> C

Return a client suitable for read operations.

Prefers the rw client if it's already been used successfully (rw scope grants read too).

downgrade_to_read_only method ​

python
def downgrade_to_read_only() -> None

Mark the rw scope as unavailable and build a read-only client.

Subsequent get_client_for_write calls will raise; reads use the read-only client.

try_read method ​

python
async def try_read(fn: Callable[[C], Awaitable[R]]) -> R

Run a read operation, downgrading and retrying once on invalid_scope.

Backends should wrap their reads with this so an API client provisioned with only the read-only scope (e.g. sfcc.scripts) can still read through SCAPI. Writes do not go through this helper — they always require rw, and get_client_for_write already raises after a downgrade.

SiteCustomCartridges ​

python
class SiteCustomCartridges(BaseModel)

Fields

NameTypeDefault
customCartridgesstrField(..., max_length=4000)

SitePreferences ​

python
class SitePreferences(BaseModel)

Represents custom preferences at the site level within a preference group. Custom preference attributes are returned with the "c_" prefix.

Fields

NameTypeDefault
siteSite | NoneNone

SlasClientConfig ​

python
class SlasClientConfig

Configuration for creating a SLAS client.

Fields

NameTypeDefault
short_codestr
middleware_registryMiddlewareRegistry | Nonefield(default=None)

TlsOptions ​

python
class TlsOptions

TLS options for creating a transport.

Attributes

NameTypeDescription
certificatestr | NonePath to a PKCS12 (.p12/.pfx) certificate file.
passphrasestr | NonePassphrase for the certificate, if encrypted.
reject_unauthorizedbool | NoneWhether to reject invalid/self-signed server certificates. False disables verification (self-signed mode).

User ​

python
class User(BaseModel)

Fields

NameTypeDefault
loginstrField(..., max_length=256, min_length=1)
passwordstr | NoneField(None, max_length=256)
emailstrField(..., max_length=256)
firstNamestr | NoneField(None, max_length=256)
lastNamestr | NoneField(None, max_length=256)
externalIdstr | NoneField(None, max_length=256)
disabledbool | NoneNone
lockedbool | NoneNone
lastLoginDatedate | NoneNone
passwordExpirationDateAwareDatetime | NoneNone
passwordModificationDateAwareDatetime | NoneNone
preferredDataLocaleLanguageCountry | LanguageCode | DefaultFallback | NoneNone
preferredUiLocaleLanguageCountry | LanguageCode | DefaultFallback | NoneNone
roleslist[Role] | NoneNone

UserSearch ​

python
class UserSearch(PaginatedResultBase)

Fields

NameType
datalist[Datum]

UserUpdateRequest ​

python
class UserUpdateRequest(BaseModel)

Fields

NameTypeDefault
emailstr | NoneField(None, max_length=256)
firstNamestr | NoneField(None, max_length=256)
lastNamestr | NoneField(None, max_length=256)
externalIdstr | NoneField(None, max_length=256)
preferredDataLocaleLanguageCountry | LanguageCode | DefaultFallback | NoneNone
preferredUiLocaleLanguageCountry | LanguageCode | DefaultFallback | NoneNone

WebDavClient ​

python
class WebDavClient

WebDAV client for B2C Commerce instance file operations.

Parameters

NameTypeDescription
hostnamestrWebDAV hostname (may differ from the API hostname).
authAuthStrategyAuthentication strategy used for requests (its fetch injects credentials and handles TLS/mTLS).
middleware_registryMiddlewareRegistry | NoneRegistry supplying webdav middleware (defaults to the global registry).
transporthttpx.AsyncBaseTransport | NoneOptional TLS/mTLS transport passed through to auth.fetch.

build_url method ​

python
def build_url(path: str) -> str

Build the full URL for a WebDAV path (relative to /webdav/Sites/).

request method ​

python
async def request(path: str, *, method: str = 'GET', headers: dict[str, str] | None = None, content: bytes | str | None = None) -> httpx.Response

Make a raw WebDAV request, applying webdav middleware and auth.

Raises

mkcol method ​

python
async def mkcol(path: str) -> None

Create a directory (collection). Tolerates 405 (already exists).

put method ​

python
async def put(path: str, content: bytes | str, content_type: str | None = None) -> None

Upload a file to path.

get method ​

python
async def get(path: str) -> bytes

Download a file, returning its content as bytes.

delete method ​

python
async def delete(path: str) -> None

Delete a file or directory.

propfind method ​

python
async def propfind(path: str, depth: str = '1') -> list[PropfindEntry]

List directory contents via PROPFIND (depth is "0", "1", or "infinity").

copy method ​

python
async def copy(source: str, destination: str, overwrite: bool = True) -> None

Copy a file or directory from source to destination.

move method ​

python
async def move(source: str, destination: str, overwrite: bool = True) -> None

Move (rename) a file or directory from source to destination.

exists method ​

python
async def exists(path: str) -> bool

Return True if path exists (via a HEAD request).

Zone ​

python
class Zone(RootModel[str])

Fields

NameType
rootstr

ZonesEnvelope ​

python
class ZonesEnvelope(BaseModel)

Fields

NameType
datalist[Zone2]

Functions ​

assert_ocapi_compatibility_allowed ​

python
def assert_ocapi_compatibility_allowed(preference: ApiBackendPreference | None, capability: str) -> None

Prevent an OCAPI-only compatibility operation from running under explicit SCAPI.

auto remains eligible for the temporary compatibility path, while explicit OCAPI is always allowed.

assert_scapi_admin_auth_supported ​

python
def assert_scapi_admin_auth_supported(auth: AuthStrategy) -> None

Reject browser user-auth strategies before a SCAPI request is attempted.

build_scapi_client ​

python
def build_scapi_client(options: BuildScapiClientOptions, config: ScapiClientConfig, auth: AuthStrategy) -> HttpClient

Build a typed HTTP client for a SCAPI Admin API.

Parameters

NameTypeDescription
optionsBuildScapiClientOptionsDomain-specific URL/key/scopes/log-prefix.
configScapiClientConfigCaller-supplied short code, tenant ID, optional overrides.
authAuthStrategyAuth strategy (scopes are merged via with_scopes).

Raises

  • ValueError — if neither or both of scope_cascade/default_scopes are provided.

build_tenant_scope ​

python
def build_tenant_scope(tenant_id: str) -> str

Build the tenant-specific OAuth scope required for SCAPI APIs.

python
>>> build_tenant_scope("zzxy_prd")
'SALESFORCE_COMMERCE_API:zzxy_prd'
>>> build_tenant_scope("f_ecom_zzxy_prd")
'SALESFORCE_COMMERCE_API:zzxy_prd'

change_api_client_password ​

python
async def change_api_client_password(client: AccountManagerApiClientsClient, api_client_id: str, old_password: str, new_password: str) -> None

Change the password for an API client.

create_account_manager_api_clients_client ​

python
def create_account_manager_api_clients_client(config: AccountManagerClientConfig, auth: AuthStrategy) -> AccountManagerApiClientsClient

Create a typed Account Manager API Clients API client.

Parameters

NameTypeDescription
configAccountManagerClientConfigAccount Manager client configuration.
authAuthStrategyAuthentication strategy (typically OAuth).

Returns: A configured HttpClient.

create_account_manager_client ​

python
def create_account_manager_client(config: AccountManagerClientConfig, auth: AuthStrategy) -> AccountManagerClient

Create a unified Account Manager API client (users, roles, API clients, orgs).

Parameters

NameTypeDescription
configAccountManagerClientConfigAccount Manager client configuration.
authAuthStrategyAuthentication strategy (typically OAuth).

Returns: A unified AccountManagerClient.

create_account_manager_orgs_client ​

python
def create_account_manager_orgs_client(config: AccountManagerClientConfig, auth: AuthStrategy) -> AccountManagerOrgsClient

Create an Account Manager Organizations API client.

Parameters

NameTypeDescription
configAccountManagerClientConfigAccount Manager Organizations client configuration.
authAuthStrategyAuthentication strategy (typically OAuth).

Returns: An AccountManagerOrgsClient.

create_account_manager_roles_client ​

python
def create_account_manager_roles_client(config: AccountManagerClientConfig, auth: AuthStrategy) -> AccountManagerRolesClient

Create a typed Account Manager Roles API client.

Parameters

NameTypeDescription
configAccountManagerClientConfigAccount Manager Roles client configuration.
authAuthStrategyAuthentication strategy (typically OAuth).

Returns: A configured HttpClient.

create_account_manager_users_client ​

python
def create_account_manager_users_client(config: AccountManagerClientConfig, auth: AuthStrategy) -> AccountManagerUsersClient

Create a typed Account Manager Users API client.

Parameters

NameTypeDescription
configAccountManagerClientConfigAccount Manager Users client configuration.
authAuthStrategyAuthentication strategy (typically OAuth).

Returns: A configured HttpClient.

create_api_client ​

python
async def create_api_client(client: AccountManagerApiClientsClient, body: APIClientCreate) -> AccountManagerApiClient

Create a new API client.

Omits active when False so the API uses its default (inactive); some implementations reject or mishandle explicit active: false and return "invalid argument APIClient".

create_auth_middleware ​

python
def create_auth_middleware(auth: Any) -> _AuthMiddleware

Create authentication middleware that injects the auth header and retries on 401.

On a 401 following a prior successful response (indicating token expiry rather than bad credentials), it invalidates the token and retries the request once with a fresh token. Requires the strategy to implement get_authorization_header and invalidate_token.

create_cdn_zones_client ​

python
def create_cdn_zones_client(config: CdnZonesClientConfig, auth: AuthStrategy, options: CdnZonesClientOptions | None = None) -> CdnZonesClient

Create a typed CDN Zones API client.

The client automatically handles OAuth scope requirements:

  • Domain scope: sfcc.cdn-zones (read) or sfcc.cdn-zones.rw (read-write)
  • Tenant scope: SALESFORCE_COMMERCE_API:{tenant_id}

Parameters

NameTypeDescription
configCdnZonesClientConfigCDN Zones client configuration including short code and tenant ID.
authAuthStrategyAuthentication strategy (typically OAuth).
optionsCdnZonesClientOptions | NoneOptional settings such as read_write.

Returns: A configured HttpClient.

create_custom_apis_client ​

python
def create_custom_apis_client(config: CustomApisClientConfig, auth: AuthStrategy) -> CustomApisClient

Create a typed Custom APIs DX API client.

The client automatically handles OAuth scope requirements:

  • Domain scope: sfcc.custom-apis (or custom via config.scopes)
  • Tenant scope: SALESFORCE_COMMERCE_API:{tenant_id}

Parameters

NameTypeDescription
configCustomApisClientConfigCustom APIs client configuration including short code and tenant ID.
authAuthStrategyAuthentication strategy (typically OAuth).

Returns: A configured HttpClient.

create_dual_backend ​

python
def create_dual_backend(config: DualBackendConfig, ctors: DualBackendCtors[T]) -> T

Resolve a preference + config availability into a concrete backend instance.

Parameters

NameTypeDescription
configDualBackendConfigThe instance + optional backend preference.
ctorsDualBackendCtors[T]Per-domain SCAPI/OCAPI constructors and domain name.

Raises

  • ValueError — when explicit SCAPI is requested without SCAPI config.

create_extra_params_middleware ​

python
def create_extra_params_middleware(*, query: dict[str, Any] | None = None, body: dict[str, Any] | None = None, headers: dict[str, str] | None = None) -> _ExtraParamsMiddleware

Create middleware that adds extra query params, body fields, and/or headers.

Useful for internal/power-user parameters not present in the typed schema.

create_fallback_backend ​

python
def create_fallback_backend(scapi: T, ocapi: T, domain_name: str) -> T

Create a fallback wrapper over scapi and ocapi backends.

The returned object presents the same interface as T. Method calls are intercepted: the first call tries SCAPI; on a safe fallback trigger it falls back to OCAPI and re-pins. The name property reflects the resolved backend.

Parameters

NameTypeDescription
scapiTPrimary (SCAPI) backend implementation.
ocapiTFallback (OCAPI) backend implementation.
domain_namestrUsed in fallback log messages, e.g. "jobs".

Returns: A wrapper over scapi whose methods route through fallback logic.

create_granular_replications_client ​

python
def create_granular_replications_client(config: GranularReplicationsClientConfig, auth: AuthStrategy) -> GranularReplicationsClient

Create a Granular Replications API client for publishing individual items.

The Granular Replications API enables programmatic publishing of individual items (products, price tables, content assets) from staging to production environments.

Parameters

NameTypeDescription
configGranularReplicationsClientConfigClient configuration with short code and tenant ID.
authAuthStrategyOAuth authentication strategy.

Returns: A configured HttpClient.

create_logging_middleware ​

python
def create_logging_middleware(config: str | dict[str, Any] | None = None) -> _LoggingMiddleware

Create logging middleware. Pass a prefix string, or a config dict with prefix and mask_body_keys (top-level body keys masked in logs).

create_metrics_client ​

python
def create_metrics_client(config: MetricsClientConfig, auth: AuthStrategy) -> MetricsClient

Create a typed Metrics API client.

The client automatically handles OAuth scope requirements:

  • Domain scope: sfcc.metrics (or custom via config.scopes)
  • Tenant scope: SALESFORCE_COMMERCE_API:{tenant_id}

Parameters

NameTypeDescription
configMetricsClientConfigMetrics client configuration including short code and tenant ID.
authAuthStrategyAuthentication strategy (typically OAuth client-credentials).

Returns: A configured HttpClient.

create_mrt_b2c_client ​

python
def create_mrt_b2c_client(config: MrtB2CClientConfig, auth: AuthStrategy) -> MrtB2CClient

Create a typed Managed Runtime B2C Commerce API client.

This client handles the B2C Commerce integration endpoints, which manage the connection between MRT targets/environments and B2C Commerce instances. Authentication is handled via the auth middleware (typically backed by an API-key strategy) rather than the SCAPI OAuth scope cascade.

Parameters

NameTypeDescription
configMrtB2CClientConfigMRT B2C client configuration.
authAuthStrategyAuthentication strategy (typically an API-key strategy).

Returns: A configured HttpClient.

create_mrt_client ​

python
def create_mrt_client(config: MrtClientConfig, auth: AuthStrategy) -> MrtClient

Create a typed Managed Runtime API client.

Authentication is handled via the auth middleware (typically backed by an API-key strategy) rather than the SCAPI OAuth scope cascade.

Parameters

NameTypeDescription
configMrtClientConfigMRT client configuration.
authAuthStrategyAuthentication strategy (typically an API-key strategy).

Returns: A configured HttpClient.

create_ocapi_client ​

python
def create_ocapi_client(hostname: str, auth: AuthStrategy, options: dict[str, Any] | str | None = None, *, transport: Any = None) -> OcapiClient

Create an OCAPI Data API client.

Parameters

NameTypeDescription
hostnamestrB2C instance hostname.
authAuthStrategyAuthentication strategy (typically OAuth).
optionsdict[str, Any] | str | NoneOptional {"api_version": ..., "middleware_registry": ...} dict, or a bare string for the API version (backwards compatibility).
transportAnyOptional TLS/mTLS transport for the underlying client.

Returns: A configured HttpClient for OCAPI.

create_ods_client ​

python
def create_ods_client(config: OdsClientConfig, auth: AuthStrategy) -> OdsClient

Create a typed ODS (On-Demand Sandbox) API client.

Parameters

NameTypeDescription
configOdsClientConfigODS client configuration.
authAuthStrategyAuthentication strategy (typically OAuth).

Returns: A configured HttpClient.

create_preferences_client ​

python
def create_preferences_client(config: PreferencesClientConfig, auth: AuthStrategy, options: PreferencesClientOptions | None = None) -> PreferencesClient

Create a typed Preferences API client.

Authentication is handled by middleware. The client automatically attaches:

  • Domain scope: sfcc.preferences (read) or sfcc.preferences.rw (read-write)
  • Tenant scope: SALESFORCE_COMMERCE_API:{tenant_id}

Parameters

NameTypeDescription
configPreferencesClientConfigPreferences client configuration including short code and tenant ID.
authAuthStrategyAuthentication strategy (typically OAuth).
optionsPreferencesClientOptions | NoneOptional settings such as read_write.

Returns: A configured HttpClient.

create_rate_limit_middleware ​

python
def create_rate_limit_middleware(*, max_retries: int = DEFAULT_RATE_LIMIT_MAX_RETRIES, base_delay_ms: float = DEFAULT_RATE_LIMIT_BASE_DELAY_MS, max_delay_ms: float = DEFAULT_RATE_LIMIT_MAX_DELAY_MS, status_codes: list[int] | None = None, prefix: str | None = None) -> _RateLimitMiddleware

Create rate-limiting middleware for the typed clients.

Inspects responses for rate-limit status codes (default [429]), uses the Retry-After header when present, otherwise exponential backoff with jitter (base 1s, max 30s), and retries up to max_retries times.

create_scapi_auth_middleware ​

python
def create_scapi_auth_middleware(auth: Any, cascade: ScopeCascade) -> _ScapiAuthMiddleware

Create SCAPI auth middleware that resolves a ScopeCascade per request.

Reads SCOPE_MODE_HEADER, picks the matching cascade, and asks the auth strategy to resolve it (cache-first, then AM with invalid_scope fallback). Strips the header before the request is sent. Falls back to get_authorization_header when the strategy lacks get_access_token_for_cascade or no scope-mode header was supplied. 401 retry matches create_auth_middleware.

create_scapi_catalogs_client ​

python
def create_scapi_catalogs_client(config: ScapiCatalogsClientConfig, auth: AuthStrategy) -> ScapiCatalogsClient

Create a typed SCAPI Catalogs Admin API client.

Parameters

NameTypeDescription
configScapiCatalogsClientConfigSCAPI client configuration including short code and tenant ID.
authAuthStrategyAuthentication strategy (typically OAuth).

Returns: A configured HttpClient.

create_scapi_jobs_client ​

python
def create_scapi_jobs_client(config: ScapiJobsClientConfig, auth: AuthStrategy) -> ScapiJobsClient

Create a typed SCAPI Jobs Admin API client.

Parameters

NameTypeDescription
configScapiJobsClientConfigSCAPI client configuration including short code and tenant ID.
authAuthStrategyAuthentication strategy (typically OAuth).

Returns: A configured HttpClient.

create_scapi_merchant_roles_client ​

python
def create_scapi_merchant_roles_client(config: ScapiMerchantRolesClientConfig, auth: AuthStrategy) -> ScapiMerchantRolesClient

Create a typed SCAPI Merchant Roles Admin API client.

Parameters

NameTypeDescription
configScapiMerchantRolesClientConfigSCAPI client configuration including short code and tenant ID.
authAuthStrategyAuthentication strategy (typically OAuth).

Returns: A configured HttpClient.

create_scapi_merchant_users_client ​

python
def create_scapi_merchant_users_client(config: ScapiMerchantUsersClientConfig, auth: AuthStrategy) -> ScapiMerchantUsersClient

Create a typed SCAPI Merchant Users Admin API client.

Parameters

NameTypeDescription
configScapiMerchantUsersClientConfigSCAPI client configuration including short code and tenant ID.
authAuthStrategyAuthentication strategy (typically OAuth).

Returns: A configured HttpClient.

create_scapi_request_error ​

python
def create_scapi_request_error(error: object, response: Any, fallback_message: str) -> ScapiRequestError

Create a structured SCAPI error using the repository's common formatter.

Parameters

NameTypeDescription
responseAnyAn object exposing status (and optionally status_text), e.g. an httpx.Response or a lightweight status holder.

create_scapi_schemas_client ​

python
def create_scapi_schemas_client(config: ScapiSchemasClientConfig, auth: AuthStrategy) -> ScapiSchemasClient

Create a typed SCAPI Schemas API client.

The client automatically handles OAuth scope requirements:

  • Domain scope: sfcc.scapi-schemas (or custom via config.scopes)
  • Tenant scope: SALESFORCE_COMMERCE_API:{tenant_id}

Parameters

NameTypeDescription
configScapiSchemasClientConfigSCAPI Schemas client configuration including short code and tenant ID.
authAuthStrategyAuthentication strategy (typically OAuth).

Returns: A configured HttpClient.

create_scapi_scripts_client ​

python
def create_scapi_scripts_client(config: ScapiScriptsClientConfig, auth: AuthStrategy) -> ScapiScriptsClient

Create a typed SCAPI Scripts DX API client.

Parameters

NameTypeDescription
configScapiScriptsClientConfigSCAPI client configuration including short code and tenant ID.
authAuthStrategyAuthentication strategy (typically OAuth).

Returns: A configured HttpClient.

create_scapi_sites_client ​

python
def create_scapi_sites_client(config: ScapiSitesClientConfig, auth: AuthStrategy) -> ScapiSitesClient

Create a typed SCAPI Sites Admin API client.

Parameters

NameTypeDescription
configScapiSitesClientConfigSCAPI client configuration including short code and tenant ID.
authAuthStrategyAuthentication strategy (typically OAuth).

Returns: A configured HttpClient.

create_slas_client ​

python
def create_slas_client(config: SlasClientConfig, auth: AuthStrategy) -> SlasClient

Create a typed SLAS Admin API client.

Parameters

NameTypeDescription
configSlasClientConfigSLAS client configuration.
authAuthStrategyAuthentication strategy (typically OAuth).

Returns: A configured HttpClient.

create_tls_transport ​

python
def create_tls_transport(options: TlsOptions) -> httpx.AsyncBaseTransport | None

Create an httpx transport with custom TLS options for mTLS / self-signed certs.

Returns None when no TLS customization is needed (no certificate and reject_unauthorized not explicitly False), so callers fall back to the default transport.

Raises

  • ValueError — on unreadable or invalid certificate files, or a bad passphrase (see _load_pkcs12).

create_user ​

python
async def create_user(client: AccountManagerUsersClient, user: UserCreate) -> AccountManagerUser

Create a new user. Raises if the request fails.

create_user_agent_middleware ​

python
def create_user_agent_middleware(user_agent: str) -> _UserAgentMiddleware

Create middleware that sets User-Agent and sfdc_user_agent headers.

delete_api_client ​

python
async def delete_api_client(client: AccountManagerApiClientsClient, api_client_id: str) -> None

Delete an API client. Only clients disabled for at least 7 days can be deleted.

delete_user ​

python
async def delete_user(client: AccountManagerUsersClient, user_id: str) -> None

Disable a user (soft delete -- sets userState to DELETED).

Users must be disabled before they can be purged.

fetch_role_mapping ​

python
async def fetch_role_mapping(roles_client: AccountManagerRolesClient) -> RoleMapping

Fetch all roles and build a mapping between role id and roleEnumName.

find_user_by_login ​

python
async def find_user_by_login(client: AccountManagerUsersClient, login: str, expand: list[UserExpandOption] | None = None) -> AccountManagerUser | None

Find a user by login (email) using the dedicated search endpoint.

Returns: The user if found, None if not found.

get_api_client ​

python
async def get_api_client(client: AccountManagerApiClientsClient, api_client_id: str, expand: list[ApiClientExpandOption] | None = None) -> AccountManagerApiClient

Retrieve an API client by ID. Raises if not found (404) or the request fails.

get_api_error_message ​

python
def get_api_error_message(error: Any, response: StatusLike) -> str

Extract a clean error message from an API error response.

Handles multiple API error patterns and falls back to HTTP status so HTML response bodies (like error pages) are never surfaced. Supported patterns:

  • ODS/SLAS: {"error": {"message": "..."}}
  • OCAPI: {"fault": {"message": "..."}}
  • SCAPI/Problem+JSON: {"detail": "...", "title": "..."}
  • Standard: {"message": "..."}

get_role ​

python
async def get_role(client: AccountManagerRolesClient, role_id: str) -> AccountManagerRole

Retrieve details of a role by ID. Raises if the role is not found or the request fails.

get_user ​

python
async def get_user(client: AccountManagerUsersClient, user_id: str, expand: list[UserExpandOption] | None = None) -> AccountManagerUser

Retrieve details of a user by ID. Raises if the user is not found or the request fails.

get_user_agent ​

python
def get_user_agent() -> str

Return the current User-Agent string.

is_fallback_trigger ​

python
def is_fallback_trigger(error: object) -> bool

Detect whether an error should trigger an OCAPI fallback.

Currently:

is_invalid_scope_error ​

python
def is_invalid_scope_error(error: object) -> bool

Detect an Account Manager invalid_scope error.

When a client's API client doesn't have the requested scope configured, Account Manager returns {"error":"invalid_scope", ...} on the token request. The OAuth strategy surfaces that as an exception whose message contains invalid_scope. Used by fallback wrappers to decide whether to downgrade to OCAPI.

is_ocapi_deprecated_fault ​

python
def is_ocapi_deprecated_fault(error: Any) -> bool

Return True if an API error object is an OCAPI deprecation fault.

Detection keys off the structured fault.type, not the message text, so it is robust to message wording changes.

is_valid_role_tenant_filter ​

python
def is_valid_role_tenant_filter(value: str) -> bool

Return True if value matches the Account Manager role tenant filter format.

Format: ROLE_ENUM:realm_instance(,realm_instance)*(;ROLE_ENUM:...)*. Examples: SALESFORCE_COMMERCE_API:abcd_prd or bm-admin:tenant1,tenant2;ECOM_USER:wxyz_stg.

list_api_clients ​

python
async def list_api_clients(client: AccountManagerApiClientsClient, options: ListApiClientsOptions | None = None) -> APIClientCollection

List API clients with pagination.

list_roles ​

python
async def list_roles(client: AccountManagerRolesClient, options: ListRolesOptions | None = None) -> RoleCollection

List roles with pagination. Raises if the request fails.

list_users ​

python
async def list_users(client: AccountManagerUsersClient, options: ListUsersOptions | None = None) -> UserCollection

List users with pagination. Raises if the request fails.

normalize_tenant_id ​

python
def normalize_tenant_id(value: str) -> str

Normalize any parseable tenant/organization ID form to canonical underscore format.

Supported input forms (all resolve to abcd_123):

  • abcd_123 — canonical tenant ID (returned as-is)
  • abcd-123 — hyphenated tenant ID
  • f_ecom_abcd_123 — organization ID
  • f_ecom_abcd-123 — org ID with hyphenated tenant
  • abcd-123.dx.commercecloud.salesforce.com — sandbox hostname
python
>>> normalize_tenant_id("f_ecom_zzxy_prd")
'zzxy_prd'
>>> normalize_tenant_id("zzxy-prd")
'zzxy_prd'
>>> normalize_tenant_id("zzxy-prd.dx.commercecloud.salesforce.com")
'zzxy_prd'

ocapi_deprecated_message ​

python
def ocapi_deprecated_message(required_scopes: list[str] | None = None) -> str

Build the user-facing guidance shown when an instance has OCAPI deprecated.

Pass the SCAPI scope(s) the failed operation requires to name them in the message. Omit required_scopes for operations that have no SCAPI equivalent — the message then uses the generic sfcc.* phrasing.

purge_user ​

python
async def purge_user(client: AccountManagerUsersClient, user_id: str) -> None

Purge a user (hard delete). Users must be in DELETED state before they can be purged.

reset_user ​

python
async def reset_user(client: AccountManagerUsersClient, user_id: str) -> None

Reset a user to INITIAL state and send activation instructions.

reset_user_agent ​

python
def reset_user_agent() -> None

Reset the User-Agent to the default SDK value (primarily for testing).

resolve_from_internal_role ​

python
def resolve_from_internal_role(role_enum_name: str, mapping: RoleMapping) -> str

Resolve an internal roleEnumName to its external role id using an API-fetched role mapping.

Falls back to a generic transform (lowercase + replace underscores with hyphens) for unknown roles.

resolve_scapi_or_ocapi ​

python
def resolve_scapi_or_ocapi(opts: ResolveBackendOptions) -> Literal['ocapi', 'scapi']

Resolve a user preference + config availability into a concrete backend choice.

  • Explicit "ocapi" always returns "ocapi".
  • Explicit "scapi" requires SCAPI config and raises if missing.
  • "auto" returns "scapi" if SCAPI config is available, otherwise "ocapi".

Raises

  • ValueError — when explicit SCAPI is requested without the required configuration.

resolve_to_internal_role ​

python
def resolve_to_internal_role(role: str, mapping: RoleMapping) -> str

Resolve a role to its internal roleEnumName using an API-fetched role mapping.

Accepts either the role id (e.g. bm-admin) or roleEnumName (e.g. ECOM_ADMIN). Falls back to a generic transform (uppercase + replace hyphens with underscores) for unknown roles.

scapi_capability_unsupported_message ​

python
def scapi_capability_unsupported_message(capability: str) -> str

Build the canonical error message for a capability absent from live SCAPI schemas.

scapi_unavailable_message ​

python
def scapi_unavailable_message(domain_name: str) -> str

Message for when explicit SCAPI is requested but the instance can't reach it.

Names both reasons the SCAPI client config can be unavailable — missing coordinates OR an auth flow that can't request scopes.

set_user_agent ​

python
def set_user_agent(user_agent: str) -> None

Set the User-Agent string used for all HTTP + auth requests.

Call early in an application to override the default SDK User-Agent (the CLI uses this to set a combined CLI+SDK User-Agent).

throw_ocapi_error ​

python
def throw_ocapi_error(error: Any, response: StatusLike, prefix: str, required_scopes: list[str] | None = None) -> None

Raise a well-formed error for a failed OCAPI call.

OCAPI deprecation faults become an OcapiDeprecatedError with actionable SCAPI-setup guidance; everything else raises a plain RuntimeError of the form "{prefix}: {message}". Always raises.

to_organization_id ​

python
def to_organization_id(tenant_id: str) -> str

Ensure a tenant ID has the f_ecom_ prefix for use as a SCAPI organizationId.

If the value already has the prefix, it's returned as-is.

python
>>> to_organization_id("zzxy_prd")
'f_ecom_zzxy_prd'
>>> to_organization_id("f_ecom_zzxy_prd")
'f_ecom_zzxy_prd'

update_api_client ​

python
async def update_api_client(client: AccountManagerApiClientsClient, api_client_id: str, body: APIClientUpdate) -> AccountManagerApiClient

Update an existing API client. Raises if the request fails or the body is invalid.

update_user ​

python
async def update_user(client: AccountManagerUsersClient, user_id: str, changes: UserUpdate) -> AccountManagerUser

Update an existing user. Raises if the request fails.

with_scopes ​

python
def with_scopes(auth: AuthStrategy, additional_scopes: list[str]) -> AuthStrategy

Return a copy of auth with additional_scopes merged in.

Falls back to the original auth if the strategy doesn't support scope merging (e.g. basic/api-key auth, or a stored-session strategy where scopes were fixed at acquisition). Centralized so SCAPI client factories don't have to keep extending an isinstance chain as new OAuth strategy types are added.

Attributes ​

CDN_ZONES_READ_SCOPES ​

python
CDN_ZONES_READ_SCOPES = ['sfcc.cdn-zones']

CDN_ZONES_RW_SCOPES ​

python
CDN_ZONES_RW_SCOPES = ['sfcc.cdn-zones.rw']

CUSTOM_APIS_DEFAULT_SCOPES ​

python
CUSTOM_APIS_DEFAULT_SCOPES = ['sfcc.custom-apis']

DEFAULT_API_VERSION ​

python
DEFAULT_API_VERSION = 'v25_6'

DEFAULT_MRT_B2C_ORIGIN ​

python
DEFAULT_MRT_B2C_ORIGIN = 'https://cloud.mobify.com/api/cc/b2c'

DEFAULT_MRT_ORIGIN ​

python
DEFAULT_MRT_ORIGIN = 'https://cloud.mobify.com'

METRICS_DEFAULT_SCOPES ​

python
METRICS_DEFAULT_SCOPES = ['sfcc.metrics']

OCAPI_DEPRECATED_MESSAGE ​

python
OCAPI_DEPRECATED_MESSAGE = ocapi_deprecated_message()

ORGANIZATION_ID_PREFIX ​

python
ORGANIZATION_ID_PREFIX = 'f_ecom_'

PREFERENCES_READ_SCOPES ​

python
PREFERENCES_READ_SCOPES = ['sfcc.preferences']

PREFERENCES_RW_SCOPES ​

python
PREFERENCES_RW_SCOPES = ['sfcc.preferences.rw']

ROLE_TENANT_FILTER_PATTERN ​

python
ROLE_TENANT_FILTER_PATTERN = re.compile('^(\\w+:\\w{4,}_\\w{3,}(,\\w{4,}_\\w{3,})*(;)?)*$', re.ASCII)

SAFE_SCAPI_FALLBACK_STATUSES ​

python
SAFE_SCAPI_FALLBACK_STATUSES: frozenset[int] = frozenset({400, 401, 403, 404, 405, 406, 415})

SCAPI_CAPABILITY_BASELINE_RELEASE ​

python
SCAPI_CAPABILITY_BASELINE_RELEASE = '26.8'

SCAPI_CATALOGS_CASCADE ​

python
SCAPI_CATALOGS_CASCADE = ScopeCascade(read=[['sfcc.catalogs.rw'], ['sfcc.catalogs']], write=[['sfcc.catalogs.rw']])

SCAPI_JOBS_CASCADE ​

python
SCAPI_JOBS_CASCADE = ScopeCascade(read=[['sfcc.jobs.rw'], ['sfcc.jobs']], write=[['sfcc.jobs.rw']])

SCAPI_MERCHANT_ROLES_READ_SCOPES ​

python
SCAPI_MERCHANT_ROLES_READ_SCOPES = ['sfcc.roles']

SCAPI_MERCHANT_ROLES_RW_SCOPES ​

python
SCAPI_MERCHANT_ROLES_RW_SCOPES = ['sfcc.roles.rw']

SCAPI_MERCHANT_USERS_READ_SCOPES ​

python
SCAPI_MERCHANT_USERS_READ_SCOPES = ['sfcc.users']

SCAPI_MERCHANT_USERS_RW_SCOPES ​

python
SCAPI_MERCHANT_USERS_RW_SCOPES = ['sfcc.users.rw']

SCAPI_SCHEMAS_DEFAULT_SCOPES ​

python
SCAPI_SCHEMAS_DEFAULT_SCOPES = ['sfcc.scapi-schemas']

SCAPI_SCRIPTS_READ_SCOPES ​

python
SCAPI_SCRIPTS_READ_SCOPES = ['sfcc.scripts']

SCAPI_SCRIPTS_RW_SCOPES ​

python
SCAPI_SCRIPTS_RW_SCOPES = ['sfcc.scripts.rw']

SCAPI_SITES_CASCADE ​

python
SCAPI_SITES_CASCADE = ScopeCascade(read=[['sfcc.sites.rw'], ['sfcc.sites']], write=[['sfcc.sites.rw']])

SCAPI_TENANT_SCOPE_PREFIX ​

python
SCAPI_TENANT_SCOPE_PREFIX = 'SALESFORCE_COMMERCE_API:'

SCOPE_MODE_HEADER ​

python
SCOPE_MODE_HEADER = 'x-b2c-scope-mode'

APIClientCollection ​

python
APIClientCollection = dict[str, Any]

APIClientCreate ​

python
APIClientCreate = dict[str, Any]

APIClientUpdate ​

python
APIClientUpdate = dict[str, Any]

AccountManagerApiClient ​

python
AccountManagerApiClient = dict[str, Any]

AccountManagerApiClientsClient ​

python
AccountManagerApiClientsClient = HttpClient

AccountManagerOrganization ​

python
AccountManagerOrganization = dict[str, Any]

AccountManagerRole ​

python
AccountManagerRole = dict[str, Any]

AccountManagerRolesClient ​

python
AccountManagerRolesClient = HttpClient

AccountManagerUser ​

python
AccountManagerUser = dict[str, Any]

AccountManagerUsersClient ​

python
AccountManagerUsersClient = HttpClient

ApiBackendPreference ​

python
ApiBackendPreference = Literal['ocapi', 'scapi', 'auto']

ApiClientExpandOption ​

python
ApiClientExpandOption = Literal['organizations', 'roles']

CdnZonesClient ​

python
CdnZonesClient = HttpClient

CustomApisClient ​

python
CustomApisClient = HttpClient

GranularReplicationsClient ​

python
GranularReplicationsClient = HttpClient

HttpClientType ​

python
HttpClientType = ...

MetricsClient ​

python
MetricsClient = HttpClient

MrtB2CClient ​

python
MrtB2CClient = HttpClient

MrtClient ​

python
MrtClient = HttpClient

OcapiClient ​

python
OcapiClient = HttpClient

OdsClient ​

python
OdsClient = HttpClient

OrganizationCollection ​

python
OrganizationCollection = dict[str, Any]

PreferenceInstanceType ​

python
PreferenceInstanceType = Literal['staging', 'development', 'sandbox', 'production']

PreferencesClient ​

python
PreferencesClient = HttpClient

RoleCollection ​

python
RoleCollection = dict[str, Any]

ScapiCatalogsClient ​

python
ScapiCatalogsClient = HttpClient

ScapiCatalogsClientConfig ​

python
ScapiCatalogsClientConfig = ScapiClientConfig

ScapiJobsClient ​

python
ScapiJobsClient = HttpClient

ScapiJobsClientConfig ​

python
ScapiJobsClientConfig = ScapiClientConfig

ScapiMerchantRolesClient ​

python
ScapiMerchantRolesClient = HttpClient

ScapiMerchantRolesClientConfig ​

python
ScapiMerchantRolesClientConfig = ScapiClientConfig

ScapiMerchantUsersClient ​

python
ScapiMerchantUsersClient = HttpClient

ScapiMerchantUsersClientConfig ​

python
ScapiMerchantUsersClientConfig = ScapiClientConfig

ScapiSchemasClient ​

python
ScapiSchemasClient = HttpClient

ScapiScriptsClient ​

python
ScapiScriptsClient = HttpClient

ScapiScriptsClientConfig ​

python
ScapiScriptsClientConfig = ScapiClientConfig

ScapiSitesClient ​

python
ScapiSitesClient = HttpClient

ScapiSitesClientConfig ​

python
ScapiSitesClientConfig = ScapiClientConfig

ScopeTier ​

python
ScopeTier = Literal['rw', 'read-only']

SlasClient ​

python
SlasClient = HttpClient

UnifiedMiddleware ​

python
UnifiedMiddleware = Middleware

UserCollection ​

python
UserCollection = dict[str, Any]

UserCreate ​

python
UserCreate = dict[str, Any]

UserExpandOption ​

python
UserExpandOption = Literal['organizations', 'roles']

UserState ​

python
UserState = Literal['INITIAL', 'ENABLED', 'DELETED']

UserUpdate ​

python
UserUpdate = dict[str, Any]

global_middleware_registry ​

python
global_middleware_registry = MiddlewareRegistry()

user_agent_provider ​

python
user_agent_provider = _UserAgentProvider()