Skip to main content

Python wrapper for the Salesforce's Query API.

Project description

sfq (Salesforce Query)

sfq is a lightweight Python wrapper library designed to simplify querying Salesforce, reducing repetitive code for accessing Salesforce data.

For more varied workflows, consider using an alternative like Simple Salesforce. This library was even referenced on the Salesforce Developers Blog.

Features

  • Simplified query execution for Salesforce instances.
  • Integration with Salesforce authentication via refresh tokens.
  • Option to interact with Salesforce Tooling API for more advanced queries.

Installation

You can install the sfq library using pip:

pip install sfq

Usage

Library Querying

from sfq import SFAuth

# Initialize the SFAuth class with authentication details
sf = SFAuth(
    instance_url="https://example-dev-ed.trailblaze.my.salesforce.com",
    client_id="your-client-id-here",
    client_secret="your-client-secret-here",
    refresh_token="your-refresh-token-here"
)

# Execute a query to fetch account records
print(sf.query("SELECT Id FROM Account LIMIT 5"))

# Execute a query to fetch Tooling API data
print(sf.tooling_query("SELECT Id, FullName, Metadata FROM SandboxSettings LIMIT 5"))

Composite Batch Queries

multiple_queries = {
    "Recent Users": """
        SELECT Id, Name,CreatedDate
        FROM User
        ORDER BY CreatedDate DESC
        LIMIT 10""",
    "Recent Accounts": "SELECT Id, Name, CreatedDate FROM Account ORDER BY CreatedDate DESC LIMIT 10",
    "Frozen Users": "SELECT Id, UserId FROM UserLogin WHERE IsFrozen = true",  # If exceeds 2000 records, will paginate
}

batched_response = sf.cquery(multiple_queries)

for subrequest_identifer, subrequest_response in batched_response.items():
    print(f'"{subrequest_identifer}" returned {subrequest_response["totalSize"]} records')
>>> "Recent Users" returned 10 records
>>> "Recent Accounts" returned 10 records
>>> "Frozen Users" returned 4082 records

Collection Deletions

response = sf.cdelete(['07La0000000bYgj', '07La0000000bYgk', '07La0000000bYgl'])
>>> [{'id': '07La0000000bYgj', 'success': True, 'errors': []}, {'id': '07La0000000bYgk', 'success': True, 'errors': []}, {'id': '07La0000000bYgl', 'success': True, 'errors': []}]

Static Resources

page = sf.read_static_resource_id('081aj000009jUMXAA2')
print(f'Initial resource: {page}')
>>> Initial resource: <h1>It works!</h1>
sf.update_static_resource_name('HelloWorld', '<h1>Hello World</h1>')
page = sf.read_static_resource_name('HelloWorld')
print(f'Updated resource: {page}')
>>> Updated resource: <h1>Hello World</h1>
sf.update_static_resource_id('081aj000009jUMXAA2', '<h1>It works!</h1>')

sObject Key Prefixes

# Key prefix via IDs
print(sf.get_sobject_prefixes())
>>> {'0Pp': 'AIApplication', '6S9': 'AIApplicationConfig', '9qd': 'AIInsightAction', '9bq': 'AIInsightFeedback', '0T2': 'AIInsightReason', '9qc': 'AIInsightValue', ...}

# Key prefix via names
print(sf.get_sobject_prefixes(key_type="name"))
>>> {'AIApplication': '0Pp', 'AIApplicationConfig': '6S9', 'AIInsightAction': '9qd', 'AIInsightFeedback': '9bq', 'AIInsightReason': '0T2', 'AIInsightValue': '9qc', ...}

How to Obtain Salesforce Tokens

To use the sfq library, you'll need a client ID and refresh token. The easiest way to obtain these is by using the Salesforce CLI:

Steps to Get Tokens

  1. Install the Salesforce CLI:
    Follow the instructions on the Salesforce CLI installation page.

  2. Authenticate with Salesforce:
    Login to your Salesforce org using the following command:

    sf org login web --alias int --instance-url https://corpa--int.sandbox.my.salesforce.com
    
  3. Display Org Details:
    To get the client ID, client secret, refresh token, and instance URL, run:

    sf org display --target-org int --verbose --json
    

    The output will look like this:

    {
      "status": 0,
      "result": {
        "id": "00Daa0000000000000",
        "apiVersion": "63.0",
        "accessToken": "00Daa0000000000000!evaU3fYZEWGUrqI5rMtaS8KYbHfeqA7YWzMgKToOB43Jk0kj7LtiWCbJaj4owPFQ7CqpXPAGX1RDCHblfW9t8cNOCNRFng3o",
        "instanceUrl": "https://example-dev-ed.trailblaze.my.salesforce.com",
        "username": "user@example.com",
        "clientId": "PlatformCLI",
        "connectedStatus": "Connected",
        "sfdxAuthUrl": "force://PlatformCLI::nwAeSuiRqvRHrkbMmCKvLHasS0vRbh3Cf2RF41WZzmjtThnCwOuDvn9HObcUjKuTExJPqPegIwnLB5aH6GNWYhU@example-dev-ed.trailblaze.my.salesforce.com",
        "alias": "int"
      }
    }
    
  4. Extract and Use the Tokens:
    The sfdxAuthUrl is structured as:

    force://<client_id>:<client_secret>:<refresh_token>@<instance_url>
    

    This means with the above output sample, you would use the following information:

    # This is for illustrative purposes; use environment variables instead
    client_id = "PlatformCLI"
    client_secret = ""
    refresh_token = "nwAeSuiRqvRHrkbMmCKvLHasS0vRbh3Cf2RF41WZzmjtThnCwOuDvn9HObcUjKuTExJPqPegIwnLB5aH6GNWYhU"
    instance_url = "https://example-dev-ed.trailblaze.my.salesforce.com"
    
    from sfq import SFAuth
    sf = SFAuth(
        instance_url=instance_url,
        client_id=client_id,
        client_secret=client_secret,
        refresh_token=refresh_token,
    )
    

Important Considerations

  • Security: Safeguard your client_id, client_secret, and refresh_token diligently, as they provide access to your Salesforce environment. Avoid sharing or exposing them in unsecured locations.
  • Efficient Data Retrieval: The query and cquery function automatically handles pagination, simplifying record retrieval across large datasets. It's recommended to use the LIMIT clause in queries to control the volume of data returned.
  • Advanced Tooling Queries: Utilize the tooling_query function to access the Salesforce Tooling API. This option is designed for performing complex operations, enhancing your data management capabilities.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

sfq-0.0.26.tar.gz (17.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

sfq-0.0.26-py3-none-any.whl (15.4 kB view details)

Uploaded Python 3

File details

Details for the file sfq-0.0.26.tar.gz.

File metadata

  • Download URL: sfq-0.0.26.tar.gz
  • Upload date:
  • Size: 17.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for sfq-0.0.26.tar.gz
Algorithm Hash digest
SHA256 2daffd4ee8011c990f49e19a3df50739571e56d0dcad4f99bd7c66ce29c814df
MD5 b5214adca1956b242e26153743a21cc0
BLAKE2b-256 a714c653e9a89e9a71a76c1a9a26eb7b0798a6995106bb0b385ad7e6f20172b0

See more details on using hashes here.

Provenance

The following attestation bundles were made for sfq-0.0.26.tar.gz:

Publisher: publish.yml on dmoruzzi/sfq

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file sfq-0.0.26-py3-none-any.whl.

File metadata

  • Download URL: sfq-0.0.26-py3-none-any.whl
  • Upload date:
  • Size: 15.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for sfq-0.0.26-py3-none-any.whl
Algorithm Hash digest
SHA256 6ab5a014b1ea5d2a9bac098360d1349d25f4f8f14694419c4ba0fb8ee34d6431
MD5 28e569f3a4d45527c0e2cd9ceacd1a41
BLAKE2b-256 93f2ed428c4607c12e6e84fd1893aa62b5f88f8c5c70c2a774d454a63ffd4f39

See more details on using hashes here.

Provenance

The following attestation bundles were made for sfq-0.0.26-py3-none-any.whl:

Publisher: publish.yml on dmoruzzi/sfq

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page