sfq


Namesfq JSON
Version 0.0.32 PyPI version JSON
download
home_pageNone
SummaryPython wrapper for the Salesforce's Query API.
upload_time2025-07-20 20:16:44
maintainerNone
docs_urlNone
authorNone
requires_python>=3.9
licenseNone
keywords salesforce salesforce query
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # 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](https://simple-salesforce.readthedocs.io/en/stable/). This library was even referenced on the [Salesforce Developers Blog](https://developer.salesforce.com/blogs/2021/09/how-to-automate-data-extraction-from-salesforce-using-python).

## 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`:

```bash
pip install sfq
```

## Usage

### Library Querying

```python
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

```python
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

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

### Static Resources

```python
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

```python
# 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](https://developer.salesforce.com/tools/salesforcecli).
   
2. **Authenticate with Salesforce**:  
   Login to your Salesforce org using the following command:
   
   ```bash
   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:
   
   ```bash
   sf org display --target-org int --verbose --json
   ```

   The output will look like this:

   ```json
   {
     "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:

   ```python
   # 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.


            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "sfq",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.9",
    "maintainer_email": null,
    "keywords": "salesforce, salesforce query",
    "author": null,
    "author_email": "David Moruzzi <sfq.pypi@dmoruzi.com>",
    "download_url": "https://files.pythonhosted.org/packages/7d/b6/4fc0ddbb453c9337cb48347efa7463ffaa95bfd777882d17eda1a0bfc6c2/sfq-0.0.32.tar.gz",
    "platform": null,
    "description": "# sfq (Salesforce Query)\n\nsfq is a lightweight Python wrapper library designed to simplify querying Salesforce, reducing repetitive code for accessing Salesforce data.\n\nFor more varied workflows, consider using an alternative like [Simple Salesforce](https://simple-salesforce.readthedocs.io/en/stable/). This library was even referenced on the [Salesforce Developers Blog](https://developer.salesforce.com/blogs/2021/09/how-to-automate-data-extraction-from-salesforce-using-python).\n\n## Features\n\n- Simplified query execution for Salesforce instances.\n- Integration with Salesforce authentication via refresh tokens.\n- Option to interact with Salesforce Tooling API for more advanced queries.\n  \n## Installation\n\nYou can install the `sfq` library using `pip`:\n\n```bash\npip install sfq\n```\n\n## Usage\n\n### Library Querying\n\n```python\nfrom sfq import SFAuth\n\n# Initialize the SFAuth class with authentication details\nsf = SFAuth(\n    instance_url=\"https://example-dev-ed.trailblaze.my.salesforce.com\",\n    client_id=\"your-client-id-here\",\n    client_secret=\"your-client-secret-here\",\n    refresh_token=\"your-refresh-token-here\"\n)\n\n# Execute a query to fetch account records\nprint(sf.query(\"SELECT Id FROM Account LIMIT 5\"))\n\n# Execute a query to fetch Tooling API data\nprint(sf.tooling_query(\"SELECT Id, FullName, Metadata FROM SandboxSettings LIMIT 5\"))\n```\n\n### Composite Batch Queries\n\n```python\nmultiple_queries = {\n    \"Recent Users\": \"\"\"\n        SELECT Id, Name,CreatedDate\n        FROM User\n        ORDER BY CreatedDate DESC\n        LIMIT 10\"\"\",\n    \"Recent Accounts\": \"SELECT Id, Name, CreatedDate FROM Account ORDER BY CreatedDate DESC LIMIT 10\",\n    \"Frozen Users\": \"SELECT Id, UserId FROM UserLogin WHERE IsFrozen = true\",  # If exceeds 2000 records, will paginate\n}\n\nbatched_response = sf.cquery(multiple_queries)\n\nfor subrequest_identifer, subrequest_response in batched_response.items():\n    print(f'\"{subrequest_identifer}\" returned {subrequest_response[\"totalSize\"]} records')\n>>> \"Recent Users\" returned 10 records\n>>> \"Recent Accounts\" returned 10 records\n>>> \"Frozen Users\" returned 4082 records\n```\n\n### Collection Deletions\n\n```python\nresponse = sf.cdelete(['07La0000000bYgj', '07La0000000bYgk', '07La0000000bYgl'])\n>>> [{'id': '07La0000000bYgj', 'success': True, 'errors': []}, {'id': '07La0000000bYgk', 'success': True, 'errors': []}, {'id': '07La0000000bYgl', 'success': True, 'errors': []}]\n```\n\n### Static Resources\n\n```python\npage = sf.read_static_resource_id('081aj000009jUMXAA2')\nprint(f'Initial resource: {page}')\n>>> Initial resource: <h1>It works!</h1>\nsf.update_static_resource_name('HelloWorld', '<h1>Hello World</h1>')\npage = sf.read_static_resource_name('HelloWorld')\nprint(f'Updated resource: {page}')\n>>> Updated resource: <h1>Hello World</h1>\nsf.update_static_resource_id('081aj000009jUMXAA2', '<h1>It works!</h1>')\n```\n\n### sObject Key Prefixes\n\n```python\n# Key prefix via IDs\nprint(sf.get_sobject_prefixes())\n>>> {'0Pp': 'AIApplication', '6S9': 'AIApplicationConfig', '9qd': 'AIInsightAction', '9bq': 'AIInsightFeedback', '0T2': 'AIInsightReason', '9qc': 'AIInsightValue', ...}\n\n# Key prefix via names\nprint(sf.get_sobject_prefixes(key_type=\"name\"))\n>>> {'AIApplication': '0Pp', 'AIApplicationConfig': '6S9', 'AIInsightAction': '9qd', 'AIInsightFeedback': '9bq', 'AIInsightReason': '0T2', 'AIInsightValue': '9qc', ...}\n```\n\n## How to Obtain Salesforce Tokens\n\nTo 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:\n\n### Steps to Get Tokens\n\n1. **Install the Salesforce CLI**:  \n   Follow the instructions on the [Salesforce CLI installation page](https://developer.salesforce.com/tools/salesforcecli).\n   \n2. **Authenticate with Salesforce**:  \n   Login to your Salesforce org using the following command:\n   \n   ```bash\n   sf org login web --alias int --instance-url https://corpa--int.sandbox.my.salesforce.com\n   ```\n   \n3. **Display Org Details**:  \n   To get the client ID, client secret, refresh token, and instance URL, run:\n   \n   ```bash\n   sf org display --target-org int --verbose --json\n   ```\n\n   The output will look like this:\n\n   ```json\n   {\n     \"status\": 0,\n     \"result\": {\n       \"id\": \"00Daa0000000000000\",\n       \"apiVersion\": \"63.0\",\n       \"accessToken\": \"00Daa0000000000000!evaU3fYZEWGUrqI5rMtaS8KYbHfeqA7YWzMgKToOB43Jk0kj7LtiWCbJaj4owPFQ7CqpXPAGX1RDCHblfW9t8cNOCNRFng3o\",\n       \"instanceUrl\": \"https://example-dev-ed.trailblaze.my.salesforce.com\",\n       \"username\": \"user@example.com\",\n       \"clientId\": \"PlatformCLI\",\n       \"connectedStatus\": \"Connected\",\n       \"sfdxAuthUrl\": \"force://PlatformCLI::nwAeSuiRqvRHrkbMmCKvLHasS0vRbh3Cf2RF41WZzmjtThnCwOuDvn9HObcUjKuTExJPqPegIwnLB5aH6GNWYhU@example-dev-ed.trailblaze.my.salesforce.com\",\n       \"alias\": \"int\"\n     }\n   }\n   ```\n\n4. **Extract and Use the Tokens**:  \n   The `sfdxAuthUrl` is structured as:\n   \n   ```\n   force://<client_id>:<client_secret>:<refresh_token>@<instance_url>\n   ```\n\n   This means with the above output sample, you would use the following information:\n\n   ```python\n   # This is for illustrative purposes; use environment variables instead\n   client_id = \"PlatformCLI\"\n   client_secret = \"\"\n   refresh_token = \"nwAeSuiRqvRHrkbMmCKvLHasS0vRbh3Cf2RF41WZzmjtThnCwOuDvn9HObcUjKuTExJPqPegIwnLB5aH6GNWYhU\"\n   instance_url = \"https://example-dev-ed.trailblaze.my.salesforce.com\"\n\n   from sfq import SFAuth\n   sf = SFAuth(\n       instance_url=instance_url,\n       client_id=client_id,\n       client_secret=client_secret,\n       refresh_token=refresh_token,\n   )\n\n   ```\n\n## Important Considerations\n\n- **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.\n- **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.\n- **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.\n\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "Python wrapper for the Salesforce's Query API.",
    "version": "0.0.32",
    "project_urls": null,
    "split_keywords": [
        "salesforce",
        " salesforce query"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "6438162bb3803c5116cfe802be61fbd3811d68b0397ac6459144cb527409e0a8",
                "md5": "6ec522d4db4ebba247db87f77aad67c0",
                "sha256": "d9edf91919da3e87e10b15d87f4966077e4ac8a29fff866a75adba26a238fdf7"
            },
            "downloads": -1,
            "filename": "sfq-0.0.32-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "6ec522d4db4ebba247db87f77aad67c0",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.9",
            "size": 17549,
            "upload_time": "2025-07-20T20:16:42",
            "upload_time_iso_8601": "2025-07-20T20:16:42.304504Z",
            "url": "https://files.pythonhosted.org/packages/64/38/162bb3803c5116cfe802be61fbd3811d68b0397ac6459144cb527409e0a8/sfq-0.0.32-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "7db64fc0ddbb453c9337cb48347efa7463ffaa95bfd777882d17eda1a0bfc6c2",
                "md5": "8af25df008868624a4ea5fd1e0654039",
                "sha256": "0d4ad8f6601954f1b366d18e9d57e19af80c70a0a873ed3e5f774ab869619fbc"
            },
            "downloads": -1,
            "filename": "sfq-0.0.32.tar.gz",
            "has_sig": false,
            "md5_digest": "8af25df008868624a4ea5fd1e0654039",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.9",
            "size": 23390,
            "upload_time": "2025-07-20T20:16:44",
            "upload_time_iso_8601": "2025-07-20T20:16:44.029939Z",
            "url": "https://files.pythonhosted.org/packages/7d/b6/4fc0ddbb453c9337cb48347efa7463ffaa95bfd777882d17eda1a0bfc6c2/sfq-0.0.32.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-07-20 20:16:44",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "lcname": "sfq"
}
        
Elapsed time: 1.69445s