### Install aiosalesforce Source: https://georgebv.github.io/aiosalesforce Install the aiosalesforce library using pip. For JWT Bearer Flow authentication, install with the 'jwt' extra. ```bash pip install aiosalesforce ``` ```bash pip install aiosalesforce[jwt] ``` -------------------------------- ### Complete aiosalesforce Script Source: https://georgebv.github.io/aiosalesforce A complete example script demonstrating authentication, client creation, record creation, retrieval, and SOQL query execution. ```python import asyncio from aiosalesforce import Salesforce from aiosalesforce.auth import SoapLogin from httpx import AsyncClient async def main(): auth = SoapLogin( username="your-username", password="your-password", security_token="your-security-token", ) async with AsyncClient() as client: salesforce = Salesforce( client, base_url="https://your-instance.my.salesforce.com", auth=auth, ) contact_id = await salesforce.sobject.create( "Contact", { "FirstName": "John", "LastName": "Doe", "Email": "john.doe@example.com", }, ) print(f"Created Contact with ID: {contact_id}") contact = await salesforce.sobject.get("Contact", contact_id) print(contact) async for record in salesforce.query("SELECT Id, Name FROM Contact"): print(record) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Start Composite Batch Operation Source: https://georgebv.github.io/aiosalesforce/api-reference/composite/client Use this method to start a composite batch operation. It can be used as a context manager for automatic execution. Configure error handling with `halt_on_error`, `autoraise`, and `group_errors`. ```python async with salesforce.composite.batch(halt_on_error=True) as batch: query = batch.query("SELECT Id, Name FROM Account LIMIT 10") contact = batch.sobject.create( "Contact", {"FirstName": "Jon", "LastName": "Doe"}, ) print(query.records) print(contact.id) ``` -------------------------------- ### Formatted SOQL Query String Example Source: https://georgebv.github.io/aiosalesforce/documentation/soql This shows the resulting SOQL query string after using `format_soql` with a string parameter. ```sql SELECT Id, Name FROM Account WHERE Name = 'My Account' ``` -------------------------------- ### __call__ Source: https://georgebv.github.io/aiosalesforce/api-reference/composite/client Starts a Composite operation. Subrequests can be added and executed, or a context manager can be used for automatic execution. ```APIDOC ## `__call__` ### Description Start a Comsposite operation. To execute a composite request, add subrequests to it and call `execute`. Alternatively, use a context manager to automatically execute the request. ### Parameters #### Query Parameters - `all_or_none` (bool) - Optional - If True, all subrequests are rolled back if any subrequest fails. Default: False - `collate_subrequests` (bool) - Optional - If True, independent subrequests are executed by Salesforce in parallel. Default: True - `autoraise` (bool) - Optional - If True, raises an ExceptionGroup if any subrequest fails. Default: False ### Returns - CompositeRequest: Composite request. ### Example ```python async with salesforce.composite(all_or_none=True) as batch: account = composite.sobject.create( "Account", {...}, ) contact = composite.sobject.create( "Contact", {"Account": account.reference.id, ...} ) print(account.id) print(contact.id) ``` ``` -------------------------------- ### `__call__` Source: https://georgebv.github.io/aiosalesforce/api-reference/composite/client Starts a Composite operation. This method can be used directly or as a context manager to execute composite requests. ```APIDOC ## `__call__(all_or_none=False, collate_subrequests=False, autoraise=False)` ### Description Starts a Comsposite operation. To execute a composite request, add subrequests to it and call `execute`. Alternatively, use a context manager to automatically execute the request. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method This is a method call, not an HTTP request. ### Endpoint N/A ### Parameters - **all_or_none** (bool) - Optional - If True, all subrequests are rolled back if any subrequest fails. Defaults to `False`. - **collate_subrequests** (bool) - Optional - If True, independent subrequests are executed by Salesforce in parallel. Defaults to `True`. - **autoraise** (bool) - Optional - If True, raises an ExceptionGroup if any subrequest fails. Defaults to `False`. ### Request Example ```python async with salesforce.composite(all_or_none=True) as batch: account = composite.sobject.create( "Account", {...}, ) contact = composite.sobject.create( "Contact", {"Account": account.reference.id, ...} ) print(account.id) print(contact.id) ``` ### Response #### Success Response - **CompositeRequest** (CompositeRequest) - Composite request object. ``` -------------------------------- ### Start Composite Operation with Context Manager Source: https://georgebv.github.io/aiosalesforce/api-reference/composite/client Use this context manager to automatically execute a composite request. Configure rollback behavior with `all_or_none`. ```python async with salesforce.composite(all_or_none=True) as batch: account = composite.sobject.create( "Account", {...}, ) contact = composite.sobject.create( "Contact", {"Account": account.reference.id, ...} ) print(account.id) print(contact.id) ``` -------------------------------- ### batch Source: https://georgebv.github.io/aiosalesforce/api-reference/composite/client Starts a Composite Batch operation. Subrequests can be added and executed, or a context manager can be used for automatic execution. ```APIDOC ## `batch` ### Description Start a Comsposite Batch operation. To execute a batch request, add subrequests to the batch and call `execute`. Alternatively, use a context manager to automatically execute the batch. ### Parameters #### Query Parameters - `halt_on_error` (bool) - Optional - If True, unprocessed subrequests will be halted if any subrequest fails. Default: False - `autoraise` (bool) - Optional - If True, an exception will be raised if any subrequest fails. Default: False - `group_errors` (bool) - Optional - Ignored if `autoraise` is False. If True, raises an ExceptionGroup with all errors. Otherwise, raises the first exception. Default: False ### Returns - CompositeBatchRequest: Composite Batch request. ### Example ```python async with salesforce.composite.batch(halt_on_error=True) as batch: query = batch.query("SELECT Id, Name FROM Account LIMIT 10") contact = batch.sobject.create( "Contact", {"FirstName": "Jon", "LastName": "Doe"}, ) print(query.records) print(contact.id) ``` ``` -------------------------------- ### Start a Composite Batch Operation Source: https://georgebv.github.io/aiosalesforce/api-reference/composite/client Use this method to initiate a composite batch request. Subrequests can be added to the batch, and it can be executed using a context manager for automatic execution. Configure error handling with `halt_on_error`, `autoraise`, and `group_errors`. ```python class CompositeClient: """ Salesforce REST API Composite client. Parameters ---------- salesforce_client : Salesforce Salesforce client. """ salesforce_client: "Salesforce" def __init__(self, salesforce_client: "Salesforce") -> None: self.salesforce_client = salesforce_client def batch( self, halt_on_error: bool = False, autoraise: bool = False, group_errors: bool = False, ) -> CompositeBatchRequest: """ Start a Comsposite Batch operation. To execute a batch request, add subrequests to the batch and call `execute`. Alternatively, use a context manager to automatically execute the batch. Parameters ---------- halt_on_error : bool, default False If True, unprocessed subrequests will be halted if any subrequest fails. autoraise : bool, default False If True, an exception will be raised if any subrequest fails. group_errors : bool, default False Ignored if `autoraise` is False. If True, raises an ExceptionGroup with all errors. Otherwise, raises the first exception. Returns ------- CompositeBatchRequest Composite Batch request. Examples -------- >>> async with salesforce.composite.batch(halt_on_error=True) as batch: ... query = batch.query("SELECT Id, Name FROM Account LIMIT 10") ... contact = batch.sobject.create( ... "Contact", ... {"FirstName": "Jon", "LastName": "Doe"}, ... ) ... print(query.records) ... print(contact.id) """ return CompositeBatchRequest( salesforce_client=self.salesforce_client, halt_on_error=halt_on_error, autoraise=autoraise, group_errors=group_errors, ) ``` -------------------------------- ### Start a Composite Operation Source: https://georgebv.github.io/aiosalesforce/api-reference/composite/client Initiate a composite request, which can include multiple subrequests. Use a context manager for automatic execution. Configure rollback behavior with `all_or_none` and parallel execution with `collate_subrequests`. Error handling is managed by `autoraise`. ```python def __call__( self, all_or_none: bool = False, collate_subrequests: bool = False, autoraise: bool = False, ) -> CompositeRequest: """ Start a Comsposite operation. To execute a composite request, add subrequests to it and call `execute`. Alternatively, use a context manager to automatically execute the request. Parameters ---------- all_or_none : bool, default False If True, all subrequests are rolled back if any subrequest fails. collate_subrequests : bool, default True If True, independent subrequests are executed by Salesforce in parallel. autoraise : bool, default False If True, raises an ExceptionGroup if any subrequest fails. Returns ------- CompositeRequest Composite request. Examples -------- >>> async with salesforce.composite(all_or_none=True) as batch: ... account = composite.sobject.create( ... "Account", ... {...}, ... ) ... contact = composite.sobject.create( ... "Contact", ... {"Account": account.reference.id, ...} ... ) ... print(account.id) ... print(contact.id) """ return CompositeRequest( salesforce_client=self.salesforce_client, all_or_none=all_or_none, collate_subrequests=collate_subrequests, autoraise=autoraise, ) ``` -------------------------------- ### Track Salesforce API Usage Metrics Source: https://georgebv.github.io/aiosalesforce/documentation/client Implement a callback function to track Salesforce API usage by subscribing to `RestApiCallConsumptionEvent` and `BulkApiBatchConsumptionEvent`. This example demonstrates sending metrics to a service like AWS CloudWatch. ```python from aiosalesforce import ( Event, BulkApiBatchConsumptionEvent, RestApiCallConsumptionEvent, ) def track_api_usage(event: Event): match event: case RestApiCallConsumptionEvent(): my_metrics_service.put_metric_data( Namespace="Salesforce", MetricData=[ { "MetricName": "Salesforce REST API Call Count", "Value": event.count, "Unit": "Count", }, ], ) case BulkApiBatchConsumptionEvent(): my_metrics_service.put_metric_data( Namespace="Salesforce", MetricData=[ { "MetricName": "Salesforce Bulk API Batch Count", "Value": event.count, "Unit": "Count", }, ], ) salesforce.event_bus.subscribe_callback(track_api_usage) ``` -------------------------------- ### Set Concurrency Limit for Salesforce Client Source: https://georgebv.github.io/aiosalesforce/documentation/client Instantiate the Salesforce client with a custom concurrency limit to manage simultaneous API requests. This example sets the limit to 25, which is lower than the default of 100. ```python salesforce = Salesforce( client=client, base_url="https://your-instance.my.salesforce.com", auth=auth, concurrency_limit=25, ) ``` -------------------------------- ### Perform sObject CRUD Operations in Composite Source: https://georgebv.github.io/aiosalesforce/documentation/composite/composite Execute multiple sObject operations (update, upsert, create) within a single composite request. This example demonstrates updating an Account, upserting a Contact using an external ID, and creating an Appointment related to the Contact. ```python async with salesforce.composite(all_or_none=True) as composite: account = composite.sobject.update( "Account", "0011R00001K1H2IQAV", {"Name": "New Name"}, ) contact = composite.sobject.upsert( "Contact", "ExternalId__c", { "ExternalId__c": "123", "FirstName": "Jon", "LastName": "Doe", "AccountId": account.reference.id, }, ) appointment = composite.sobject.create( "Appointment__c", { "Name__c": "Treatment 123", "Contact__c": contact.reference.id, }, ) print("Updated account:", account.id) print("Upserted contact:", contact.id) print("Created appointment:", appointment.id) ``` -------------------------------- ### Initialize Salesforce Client Source: https://georgebv.github.io/aiosalesforce/api-reference/client Instantiate the Salesforce client with required parameters like httpx_client, base_url, and auth. Optional parameters include version, event_hooks, retry_policy, and concurrency_limit. ```python class Salesforce: """ Salesforce API client. Parameters ---------- httpx_client : httpx.AsyncClient HTTP client. base_url : str Base URL of the Salesforce instance. Must be in the format: * Production : https://[MyDomainName].my.salesforce.com * Sandbox : https://[MyDomainName]-[SandboxName].sandbox.my.salesforce.com * Developer org : https://[MyDomainName].develop.my.salesforce.com auth : Auth Authentication object. version : str, optional Salesforce API version. By default, uses the latest version. event_hooks : Iterable[Callable[[Event], Awaitable[None] | None]], optional Functions or coroutines executed when an event occurs. Hooks are executed concurrently and order of execution is not guaranteed. All hooks must be thread-safe. retry_policy : RetryPolicy, optional Retry policy for requests. The default policy retries requests up to 3 times with exponential backoff and retries the following: * httpx Transport errors (excluding timeouts) * Server errors (5xx) * Row lock errors * Rate limit errors Set to None to disable retries. concurrency_limit : int, optional Maximum number of simultaneous requests to Salesforce. The default is 100. """ httpx_client: httpx.AsyncClient auth: Auth event_bus: EventBus retry_policy: RetryPolicy _semaphore: asyncio.Semaphore def __init__( self, httpx_client: httpx.AsyncClient, base_url: str, auth: Auth, version: str = "60.0", event_hooks: Iterable[Callable[[Event], Awaitable[None] | None]] | None = None, retry_policy: RetryPolicy | None = POLICY_DEFAULT, concurrency_limit: int = 100, ) -> None: self.httpx_client = httpx_client self.base_url = base_url self.auth = auth self.version = version self.event_bus = EventBus(event_hooks) self.retry_policy = retry_policy or RetryPolicy() self._semaphore = asyncio.Semaphore(concurrency_limit) @property def version(self) -> str: """API version in the format '60.0'.""" return self.__version @version.setter def version(self, value: str) -> None: if not (match_ := re.fullmatch(r"^(v)?(\d+)(\.(0)?)?$", value)): raise ValueError( f"Invalid Salesforce API version: '{value}'. " ``` -------------------------------- ### Get Salesforce Org Limits Source: https://georgebv.github.io/aiosalesforce/api-reference/client Retrieves the Salesforce org limits by making a GET request to the limits endpoint. The response is parsed as JSON. ```python import json from typing import Any async def get_limits(self) -> dict[str, Any]: """ Get Salesforce org limits. Returns ------- dict Salesforce org limits. """ response = await self.request( "GET", f"{self.base_url}/services/data/v{self.version}/limits", headers={"Accept": "application/json"}, ) return json.loads(response.content) ``` -------------------------------- ### Create Salesforce Client Source: https://georgebv.github.io/aiosalesforce/documentation/client Instantiate the Salesforce client with necessary authentication and base URL. Ensure you have an httpx.AsyncClient instance and valid SoapLogin credentials. ```python from aiosalesforce import Salesforce, SoapLogin from httpx import AsyncClient auth = SoapLogin( username="username", password="password", security_token="security-token", ) async def main(): async with AsyncClient() as client: salesforce = Salesforce( client=client, base_url="https://your-instance.my.salesforce.com", auth=auth, ) # Your code here ... ``` -------------------------------- ### BulkClientV2 Initialization Source: https://georgebv.github.io/aiosalesforce/api-reference/bulk/v2/client Initializes the BulkClientV2 with a Salesforce client instance. ```APIDOC ## BulkClientV2 ### Description Salesforce Bulk API 2.0 client. Use this client to execute bulk ingest and query operations. ### Parameters #### Path Parameters - **salesforce_client** (Salesforce) - Required - Salesforce client. ``` -------------------------------- ### Sobject Get Subrequest Record Source: https://georgebv.github.io/aiosalesforce/api-reference/composite/composite Retrieves a specific sObject record using a get subrequest. This property first checks for request success and then returns the entire response body, which is asserted to be a dictionary. ```python class SobjectGetSubrequest(Subrequest): """sObject get subrequest.""" @property def record(self) -> dict: """Retrieved record.""" self.raise_for_status() assert isinstance(self.response_body, dict) return self.response_body ``` -------------------------------- ### Create Salesforce Client Source: https://georgebv.github.io/aiosalesforce Instantiate the Salesforce client using an httpx.AsyncClient and the authentication object. The base_url must be specified for your Salesforce instance. ```python async def main(): async with AsyncClient() as client: salesforce = Salesforce( client, base_url="https://your-instance.my.salesforce.com", auth=auth, ) ``` -------------------------------- ### Get sObject Record by ID or External ID Source: https://georgebv.github.io/aiosalesforce/api-reference/composite/batch Retrieves an sObject record by its ID or an external ID. Allows specifying fields to retrieve. Appends the get subrequest to the composite batch request. ```python def get( self, sobject: str, id_, /, external_id_field: str | None = None, fields: Iterable[str] | None = None, ) -> SobjectGetSubrequest: """ Get record by ID or external ID. Parameters ---------- sobject : str Salesforce object name. E.g. "Account", "Contact", etc. id_ : str Salesforce record ID or external ID (if external_id_field is provided). external_id_field : str, optional External ID field name, by default None. fields : Iterable[str], optional Fields to get for the record. By default returns all fields. Returns ------- SobbjectGetSubrequest Get subrequest. Record can be accessed via the `record` property. """ url = httpx.URL( "/".join( [ self.base_path, sobject, id_ if external_id_field is None else f"{external_id_field}/{id_}", ] ) ) if fields is not None: url = url.copy_add_param("fields", ",".join(fields)) subrequest = SobjectGetSubrequest("GET", str(url)) self.composite_batch_request.subrequests.append(subrequest) return subrequest ``` -------------------------------- ### Initialize BulkClientV2 Source: https://georgebv.github.io/aiosalesforce/api-reference/bulk/v2/client Instantiate the BulkClientV2 with a Salesforce client. The client automatically configures the base URL for Bulk API 2.0 operations. ```python client = BulkClientV2(salesforce_client) ``` -------------------------------- ### get Source: https://georgebv.github.io/aiosalesforce/api-reference/sobject Retrieves a record by its ID or an external ID. ```APIDOC ## `get` Get record by ID or external ID. ### Parameters - `sobject` (str): Salesforce object name (e.g., "Account", "Contact"). - `id_` (str): Salesforce record ID or external ID (if `external_id_field` is provided). - `external_id_field` (str, optional): External ID field name. Defaults to None. - `fields` (Iterable[str], optional): Fields to retrieve for the record. Returns all fields by default. ### Returns - `dict`: sObject data. ``` -------------------------------- ### SobjectGetSubrequest Source: https://georgebv.github.io/aiosalesforce/api-reference/composite/batch Represents an sObject get subrequest. It provides the details of the retrieved sObject record. ```APIDOC ## SobjectGetSubrequest ### Description sObject get subrequest. ### Properties - **record** (dict): Retrieved record. ``` -------------------------------- ### Initialize BulkIngestClient Source: https://georgebv.github.io/aiosalesforce/api-reference/bulk/v2/ingest Instantiate the BulkIngestClient with a BulkClientV2 instance. The base URL for ingest operations is automatically configured. ```python bulk_client: "BulkClientV2" base_url: str """ Base URL in the format https://[subdomain(s)].my.salesforce.com/services/data/v[version]/jobs/ingest""" def __init__(self, bulk_client: "BulkClientV2") -> None: self.bulk_client = bulk_client self.base_url = f"{self.bulk_client.base_url}/ingest" ``` -------------------------------- ### Get Subrequest Status Code Source: https://georgebv.github.io/aiosalesforce/api-reference/composite/composite Retrieves the HTTP status code of the subrequest's response. ```python @property def status_code(self) -> int: """HTTP status code of the subrequest response.""" return self.response["httpStatusCode"] ``` -------------------------------- ### Salesforce Client Initialization with SoapLogin Source: https://georgebv.github.io/aiosalesforce/documentation/authentication Initialize the Salesforce client with SoapLogin authentication. Ensure credentials are not hardcoded and are managed securely. ```python import asyncio from aiosalesforce import Salesforce, SoapLogin from httpx import AsyncClient auth = SoapLogin( username="username", password="password", security_token="security-token", ) async def main(): async with AsyncClient() as client: salesforce = Salesforce( client=client, base_url="https://your-instance.my.salesforce.com", auth=auth, ) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Get Subrequest Response HTTP Headers Source: https://georgebv.github.io/aiosalesforce/api-reference/composite/composite Retrieves the HTTP headers from the subrequest's response. ```python @property def response_http_headers(self) -> dict: """Subrequest response HTTP headers.""" return self.response["httpHeaders"] ``` -------------------------------- ### SobjectClient Source: https://georgebv.github.io/aiosalesforce/api-reference/sobject Initializes the SobjectClient with a Salesforce client instance. ```APIDOC ## `SobjectClient` Salesforce REST API sObject client. ### Parameters - `salesforce_client` (Salesforce): Salesforce client. (Required) ``` -------------------------------- ### Salesforce Client Initialization Source: https://georgebv.github.io/aiosalesforce/api-reference/client Instantiate the Salesforce client with necessary parameters like HTTP client, base URL, and authentication. Optional parameters allow for API version, event hooks, retry policy, and concurrency limits. ```APIDOC ## Salesforce Client Initialization ### Description Instantiate the Salesforce client with necessary parameters like HTTP client, base URL, and authentication. Optional parameters allow for API version, event hooks, retry policy, and concurrency limits. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **httpx_client** (`AsyncClient`) - Required - HTTP client. - **base_url** (`str`) - Required - Base URL of the Salesforce instance. Must be in the format: * Production : https://[MyDomainName].my.salesforce.com * Sandbox : https://[MyDomainName]-[SandboxName].sandbox.my.salesforce.com * Developer org : https://[MyDomainName].develop.my.salesforce.com - **auth** (`Auth`) - Required - Authentication object. - **version** (`str`, optional) - Salesforce API version. By default, uses the latest version (`'60.0'`). - **event_hooks** (`Iterable[Callable[[Event], Awaitable[None] | None]]`, optional) - Functions or coroutines executed when an event occurs. Hooks are executed concurrently and order of execution is not guaranteed. All hooks must be thread-safe. Defaults to `None`. - **retry_policy** (`RetryPolicy`, optional) - Retry policy for requests. The default policy retries requests up to 3 times with exponential backoff and retries the following: * httpx Transport errors (excluding timeouts) * Server errors (5xx) * Row lock errors * Rate limit errors Set to None to disable retries. Defaults to `POLICY_DEFAULT`. - **concurrency_limit** (`int`, optional) - Maximum number of simultaneous requests to Salesforce. Defaults to `100`. ### Request Example ```python from aiosalesforce import Salesforce from httpx import AsyncClient from auth import MyAuthClass # Assuming you have an Auth class async def main(): async with AsyncClient() as client: salesforce_client = Salesforce( httpx_client=client, base_url="https://your-domain.my.salesforce.com", auth=MyAuthClass(), version="58.0", concurrency_limit=50 ) # Use salesforce_client for API calls # To run this example: # import asyncio # asyncio.run(main()) ``` ### Response #### Success Response (200) N/A for initialization. #### Response Example N/A for initialization. ``` -------------------------------- ### get_limits() Source: https://georgebv.github.io/aiosalesforce/api-reference/client Get Salesforce org limits. Returns a dictionary containing the org's limits. ```APIDOC ## `get_limits()` ### Description Get Salesforce org limits. ### Method GET ### Endpoint `/services/data/v{self.version}/limits` ### Parameters This method does not take any parameters. ### Response #### Success Response (200) - **dict**: A dictionary containing Salesforce org limits. ### Response Example ```json { "MaxApiCallsPerDay": { "Max": 10000, "Remaining": 9999 } } ``` ``` -------------------------------- ### Initialize EventBus with Callbacks Source: https://georgebv.github.io/aiosalesforce/api-reference/events Instantiate an EventBus, optionally providing an initial set of callbacks to subscribe. ```python class EventBus: """ Event bus used to dispatch events to subscribed callbacks. Parameters ---------- callbacks : Iterable[Callable[[Event], Awaitable[None] | None]], optional Callbacks to subscribe to the event bus. """ _callbacks: set[CallbackType] def __init__(self, callbacks: Iterable[CallbackType] | None = None) -> None: self._callbacks = set() for callback in callbacks or []: self.subscribe_callback(callback) ``` -------------------------------- ### Get sObject Record Source: https://georgebv.github.io/aiosalesforce/documentation/sobject Retrieve a specific sObject record by its ID. By default, all fields are returned. ```python account = await salesforce.sobject.get('Account', '0012v00002Q8f4QAAR') ``` -------------------------------- ### Get Record Source: https://georgebv.github.io/aiosalesforce/api-reference/composite/composite Retrieves a Salesforce record by its ID or an external ID. Allows specifying fields to return. ```APIDOC ## GET /services/data/v[version]/sobjects ### Description Retrieves a Salesforce record by its ID or an external ID. ### Method GET ### Endpoint /services/data/v[version]/sobjects/{sobject}/{id_} ### Parameters #### Path Parameters - **sobject** (str) - Required - Salesforce object name. E.g., "Account", "Contact", etc. - **id_** (str) - Required - Salesforce record ID or external ID (if external_id_field is provided). - **external_id_field** (str) - Optional - External ID field name. Defaults to None. #### Query Parameters - **fields** (Iterable[str]) - Optional - Fields to retrieve for the record. Defaults to all fields. ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (200) - **SobjectGetSubrequest** - Get subrequest. Record can be accessed via the `record` property. #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### Initialize SobjectClient Source: https://georgebv.github.io/aiosalesforce/api-reference/sobject Instantiates the SobjectClient with a Salesforce client instance. The base URL for sObject operations is constructed during initialization. ```python class SobjectClient: """ Salesforce REST API sObject client. Parameters ---------- salesforce_client : Salesforce Salesforce client. """ salesforce_client: "Salesforce" base_url: str """Base URL in the format https://[subdomain(s)].my.salesforce.com/services/data/v[version]/sobjects""" def __init__(self, salesforce_client: "Salesforce") -> None: self.salesforce_client = salesforce_client self.base_url = "/".join( [ self.salesforce_client.base_url, "services", "data", f"v{self.salesforce_client.version}", "sobjects", ] ) ``` -------------------------------- ### Salesforce Authentication and Operations with AsyncClient Source: https://georgebv.github.io/aiosalesforce Demonstrates how to authenticate using SoapLogin, reuse the session across multiple clients, and perform create, read, and query operations on Salesforce objects asynchronously. Ensure you replace placeholder credentials and URLs with your actual Salesforce instance details. ```python from aiosalesforce import Salesforce from aiosalesforce.auth import SoapLogin import asyncio from httpx import AsyncClient auth = SoapLogin( username="your-username", password="your-password", security_token="your-security-token", ) async def main(): async with AsyncClient() as client: # Create a Salesforce client salesforce = Salesforce( client, base_url="https://your-instance.my.salesforce.com", auth=auth, ) # Create a new Contact contact_id = await salesforce.sobject.create( "Contact", { "FirstName": "John", "LastName": "Doe", "Email": "john.doe@example.com", }, ) print(f"Created Contact with ID: {contact_id}") # Read Contact by ID contact = await salesforce.sobject.get("Contact", contact_id) print(contact) # Execute a SOQL query async for record in salesforce.query("SELECT Id, Name FROM Contact"): print(record) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Get Subrequest Response Body Source: https://georgebv.github.io/aiosalesforce/api-reference/composite/composite Retrieves the body of the subrequest's response. This can be a dictionary, list, or None. ```python @property def response_body(self) -> dict | list | None: """Subrequest response body.""" return self.response["body"] ``` -------------------------------- ### SobjectGetSubrequest for sObject Retrieval Source: https://georgebv.github.io/aiosalesforce/api-reference/composite/batch Represents an sObject get subrequest. The retrieved record is accessible through the `record` property. ```python class SobjectGetSubrequest(Subrequest): """sObject get subrequest.""" @property def record(self) -> dict: """Retrieved record.""" self.raise_for_status() assert isinstance(self.result, dict) return self.result ``` -------------------------------- ### CompositeClient Source: https://georgebv.github.io/aiosalesforce/api-reference/composite/client Initializes the CompositeClient with a Salesforce client instance. ```APIDOC ## `CompositeClient` ### Description Salesforce REST API Composite client. ### Parameters #### Path Parameters - `salesforce_client` (Salesforce) - Required - Salesforce client. ``` -------------------------------- ### Get SObject Record Source: https://georgebv.github.io/aiosalesforce/api-reference/sobject Retrieves a record by its ID or an external ID. Allows specifying which fields to return. ```APIDOC ## GET /services/data/v{version}/sobjects/{sobject}/{id} ### Description Retrieves a record by its ID or an external ID. Allows specifying which fields to return. ### Method GET ### Endpoint /services/data/v{version}/sobjects/{sobject}/{id} ### Parameters #### Path Parameters - **sobject** (str) - Required - Salesforce object name. E.g. "Account", "Contact", etc. - **id_** (str) - Required - Salesforce record ID or external ID (if external_id_field is provided). - **external_id_field** (str) - Optional - External ID field name. If provided, the `id_` parameter will be treated as an external ID. #### Query Parameters - **fields** (Iterable[str]) - Optional - Fields to get for the record. By default returns all fields. ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (200) - **dict** - sObject data. #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### Create Salesforce Record Source: https://georgebv.github.io/aiosalesforce Use the `sobject.create` method to create a new record in Salesforce. Provide the object type and a dictionary of field values. ```python contact_id = await salesforce.sobject.create( "Contact", { "FirstName": "John", "LastName": "Doe", "Email": "john.doe@example.com", }, ) print(f"Created Contact with ID: {contact_id}") ``` -------------------------------- ### Get Job Information Source: https://georgebv.github.io/aiosalesforce/api-reference/bulk/v2/ingest Retrieves detailed information about a specific ingest job using its unique job ID. ```APIDOC ## GET /services/data/v[version]/jobs/ingest/{job_id} ### Description Get information about an ingest job. ### Method GET ### Endpoint /services/data/v[version]/jobs/ingest/{job_id} ### Parameters #### Path Parameters - **job_id** (string) - Required - Ingest job ID. ### Response #### Success Response (200) - **JobInfo** (object) - Job information. ``` -------------------------------- ### Initialize Salesforce Bulk API v2 Client Source: https://georgebv.github.io/aiosalesforce/api-reference/client Instantiate the BulkClientV2 for executing bulk ingest and query operations using Salesforce Bulk API 2.0. This client is accessed via the `bulk_v2` property. ```python return BulkClientV2(self) ``` -------------------------------- ### Get Salesforce Org Limits Source: https://georgebv.github.io/aiosalesforce/api-reference/client Retrieves the current limits for your Salesforce organization. This is useful for monitoring API usage. ```APIDOC ## get_limits ### Description Get Salesforce org limits. ### Method `get_limits() -> dict[str, Any]` ### Endpoint `GET /services/data/v{version}/limits` ### Parameters None ### Response #### Success Response (200) - **dict** - A dictionary containing Salesforce org limits. ### Response Example ```json { "example": { "DailyApiRequests": { "Max": 10000, "Remaining": 9999 } } } ``` ``` -------------------------------- ### Initialize SobjectSubrequestClient Source: https://georgebv.github.io/aiosalesforce/api-reference/composite/composite Instantiate the client with a CompositeRequest object. The base path is automatically configured for sObject operations. ```python client = SobjectSubrequestClient(composite_request) ``` -------------------------------- ### Get Salesforce Org Limits Source: https://georgebv.github.io/aiosalesforce/api-reference/client Retrieves the current Salesforce org limits. Requires an active client connection. ```python async def get_limits(self) -> dict[str, Any]: """ Get Salesforce org limits. Returns ------- dict Salesforce org limits. """ response = await self.request( "GET", f"{self.base_url}/services/data/v{self.version}/limits", headers={"Accept": "application/json"}, ) return json_loads(response.content) ``` -------------------------------- ### Manually Execute a Bulk V2 Job Source: https://georgebv.github.io/aiosalesforce/documentation/bulk/v2 Demonstrates the manual process of creating a bulk job, uploading data, monitoring its state, and retrieving results. Requires importing specific serialization/deserialization functions. ```python from aiosalesforce.bulk.v2._csv import ( deserialize_ingest_results, serialize_ingest_data, ) data = [ {"FirstName": "Jon", "LastName": "Doe"}, {"FirstName": "Jane", "LastName": "Doe"}, ] job = await salesforce.bulk_v2.ingest.create_job("Contact", "insert") job = await salesforce.bulk_v2.ingest.upload_job_data( job.id, serialize_ingest_data(data), ) while job.state in {"Open", "UploadComplete", "InProgress"}: await asyncio.sleep(5) job = await self.get_job(job.id) response = await salesforce.request( "GET", f"{salesforce.bulk_v2.ingest.base_url}/{job.id}/successfulResults", ) successful_results = deserialize_ingest_results(response.content) ``` -------------------------------- ### Initialize Subrequest Source: https://georgebv.github.io/aiosalesforce/api-reference/composite/composite Use this to create a new subrequest object. It requires a reference ID, HTTP method, and URL. Optional parameters include the request body and HTTP headers. ```python class Subrequest: """ Composite subrequest. Parameters ---------- reference_id : str Reference ID. method : Literal["GET", "POST", "PUT", "PATCH", "DELETE"] HTTP method. url : str Request URL. body: dict, optional Request body. http_headers: dict, optional Request headers. """ reference_id: str method: Literal["GET", "POST", "PUT", "PATCH", "DELETE"] url: str body: dict | None http_headers: dict | None __response: dict | None = None def __init__( self, reference_id: str, method: Literal["GET", "POST", "PUT", "PATCH", "DELETE"], url: str, body: dict | None = None, http_headers: dict | None = None, ) -> None: self.reference_id = reference_id self.method = method self.url = url self.body = body self.http_headers = http_headers self.__response = None ``` -------------------------------- ### Authenticate with SoapLogin Source: https://georgebv.github.io/aiosalesforce Set up SoapLogin authentication with your Salesforce credentials. Ensure you have your username, password, and security token. ```python import asyncio from aiosalesforce import Salesforce, SoapLogin from httpx import AsyncClient auth = SoapLogin( username="your-username", password="your-password", security_token="your-security-token", ) ``` -------------------------------- ### Set and Get Subrequest Response Source: https://georgebv.github.io/aiosalesforce/api-reference/composite/composite Allows setting and retrieving the response of a subrequest. Accessing the response before it's set will raise an InvalidStateError. ```python @property def response(self) -> dict: """Subrequest response.""" if self.__response is None: raise InvalidStateError("Subrequest response has not been set") return self.__response @response.setter def response(self, value: dict) -> None: self.__response = value ``` -------------------------------- ### Initialize Salesforce Composite Client Source: https://georgebv.github.io/aiosalesforce/api-reference/client Instantiate the CompositeClient for performing composite operations like Batch, Graph, sObject Tree, and Collections. This client is accessed via the `composite` property. ```python return CompositeClient(self) ``` -------------------------------- ### DuplicatesDetectedError Source: https://georgebv.github.io/aiosalesforce/api-reference/exceptions Raised when duplicates are detected, for example, when attempting to create a new record that matches an existing one based on certain criteria. ```APIDOC ## DuplicatesDetectedError ### Description Raised when duplicates are detected, e.g. when creating a new record. ### Properties - `duplicates` (list[_DuplicateRecord]): A list of detected duplicate records, each with details like ID, object type, confidence, and matching rule. ### Inheritance - `SalesforceError` ``` -------------------------------- ### Add Query Subrequest to CompositeBatchRequest Source: https://georgebv.github.io/aiosalesforce/api-reference/composite/batch Appends a GET query subrequest to the CompositeBatchRequest. Ensure the URL is correctly formatted and includes necessary parameters. ```python ).copy_add_param("q", query) subrequest = QuerySubrequest("GET", str(url)) self.subrequests.append(subrequest) return subrequest ``` -------------------------------- ### Get Record Source: https://georgebv.github.io/aiosalesforce/api-reference/composite/batch Retrieves a Salesforce record by its ID or an external ID. This method returns a subrequest object that can be added to a composite batch request. ```APIDOC ## GET /services/data/v[version]/sobjects/[Sobject]/[Id] ### Description Get record by ID or external ID. ### Method GET ### Endpoint /services/data/v[version]/sobjects/[Sobject]/[Id] ### Parameters #### Path Parameters - **sobject** (str) - Required - Salesforce object name. E.g. "Account", "Contact", etc. - **id_** (str) - Required - Salesforce record ID or external ID (if external_id_field is provided). #### Query Parameters - **external_id_field** (str) - Optional - External ID field name, by default None. - **fields** (Iterable[str]) - Optional - Fields to get for the record. By default returns all fields. ### Response #### Success Response (200) - **SobjectGetSubrequest** - Get subrequest. Record can be accessed via the `record` property. ``` -------------------------------- ### Initialize CompositeRequest Source: https://georgebv.github.io/aiosalesforce/api-reference/composite/composite Instantiate CompositeRequest with a Salesforce client and optional parameters for controlling request behavior. ```python class CompositeRequest: """ Composite request. Parameters ---------- salesforce_client : Salesforce Salesforce client. all_or_none : bool, default False If True, all subrequests are rolled back if any subrequest fails. collate_subrequests : bool, default True If True, independent subrequests are executed by Salesforce in parallel. autoraise : bool, default False If True, raises an ExceptionGroup if any subrequest fails. """ salesforce_client: "Salesforce" all_or_none: bool collate_subrequests: bool autoraise: bool __subrequests: dict[str, Subrequest] __ref_counters: dict[str, itertools.count] def __init__( self, salesforce_client: "Salesforce", all_or_none: bool = False, collate_subrequests: bool = True, autoraise: bool = False, ) -> None: self.salesforce_client = salesforce_client self.all_or_none = all_or_none self.collate_subrequests = collate_subrequests self.autoraise = autoraise self.__subrequests = {} self.__ref_counters = {} ``` -------------------------------- ### SOAP Login Authentication Instance Source: https://georgebv.github.io/aiosalesforce/documentation/authentication Create an instance of SoapLogin for authentication using username, password, and security token. This instance can be reused across multiple clients. ```python from aiosalesforce import SoapLogin auth = SoapLogin( username="username", password="password", security_token="security-token", ) ``` -------------------------------- ### Initialize JwtBearerFlow Source: https://georgebv.github.io/aiosalesforce/documentation/authentication Instantiate the JwtBearerFlow with your connected app's client ID, username, and the path to your RSA private key. ```python from aiosalesforce import JwtBearerFlow auth = JwtBearerFlow( client_id="client-id", username="username", private_key="path/to/private-key.pem", ) ``` -------------------------------- ### Initialize CompositeBatchRequest Source: https://georgebv.github.io/aiosalesforce/api-reference/composite/batch Instantiate CompositeBatchRequest with a Salesforce client and error handling options. ```python salesforce_client = Salesforce() composite_request = CompositeBatchRequest(salesforce_client, halt_on_error=True, autoraise=True, group_errors=True) ``` -------------------------------- ### Get Subrequest Reference Source: https://georgebv.github.io/aiosalesforce/api-reference/composite/composite Provides a Reference object for this subrequest, useful for chaining requests where one subrequest's output is used as input for another. ```python @property def reference(self) -> Reference: """ Reference result of this subrequest in another subrequest. Examples -------- >>> account = composite.sobject.create( ... "Account", ... {...}, ... ) ... contact = composite.sobject.create( ... "Contact", ... {"Account": account.reference.id, ...} ... ) """ return Reference(self.reference_id) ``` -------------------------------- ### Get Reference ID for Subrequest Source: https://georgebv.github.io/aiosalesforce/api-reference/composite/composite Generates a unique reference ID for a subrequest within a composite request. Ensures uniqueness by appending a counter to the subrequest name. ```python def get_reference_id(self, name: str) -> str: """ Get a unique reference ID for a subrequest. Parameters ---------- name : str Subrequest name. E.g. 'Query' or 'Contact_create'. Returns ------- str Unique reference ID. E.g., 'Query_0' or 'Contact_create_3'. """ counter = self.__ref_counters.setdefault(name.lower(), itertools.count()) return f"{name}_{next(counter)}" ``` -------------------------------- ### Initialize SobjectSubrequestClient Source: https://georgebv.github.io/aiosalesforce/api-reference/composite/batch Initializes the SobjectSubrequestClient with a CompositeBatchRequest object. Sets the base path for sObject operations. ```python class SobjectSubrequestClient: """ Client for sObject operations. Parameters ---------- composite_batch_request : CompositeBatchRequest Composite Batch request. """ composite_batch_request: "CompositeBatchRequest" base_path: str """Base path in the format /services/data/v[version]/sobjects""" def __init__(self, composite_batch_request: "CompositeBatchRequest") -> None: self.composite_batch_request = composite_batch_request self.base_path = "/".join( [ "", "services", "data", f"v{self.composite_batch_request.salesforce_client.version}", "sobjects", ] ) ``` -------------------------------- ### Get Unique Reference ID Source: https://georgebv.github.io/aiosalesforce/api-reference/composite/composite Generate a unique reference ID for a subrequest, ensuring uniqueness within the composite request. This is useful for referencing subrequest results. ```python def get_reference_id(self, name: str) -> str: """ Get a unique reference ID for a subrequest. Parameters ---------- name : str Subrequest name. E.g. 'Query' or 'Contact_create'. Returns ------- str Unique reference ID. E.g., 'Query_0' or 'Contact_create_3'. """ counter = self.__ref_counters.setdefault(name.lower(), itertools.count()) return f"{name}_{next(counter)}" ```