A faster way to work with Salesforce - Modern Python client with advanced features
Project description
forcepy ๐
A faster way to work with Salesforce data.
Forcepy transforms the way you interact with Salesforce APIs - turning complex operations into simple, Pythonic code. Build integrations, automate workflows, or migrate data with minimal effort and maximum power.
What is forcepy?
Forcepy is a modern Python client for Salesforce that makes working with the Salesforce API feel natural and intuitive. Whether you're querying data, updating records, or building complex integrations, forcepy handles the heavy lifting so you can focus on solving business problems.
Why choose forcepy?
- ๐ฏ Simple and Pythonic: Write beautiful, easy-to-read code that feels native to Python
- โก Lightning fast: Smart caching, connection pooling, and auto-retry logic built-in
- ๐ Multiple auth methods: SOAP, OAuth2, and JWT Bearer Flow - all supported
- ๐ Advanced features: Q objects, client-side filtering, composite API, bulk operations
- ๐ Developer-friendly: Full type hints, comprehensive docs, and helpful error messages
- ๐ Beginner-friendly: Object discovery, ID lookup, and intuitive query building
Installation
# Basic installation
pip install forcepy
# With JWT support
pip install forcepy[jwt]
# Using uv (recommended)
uv add forcepy
Quickstart
A little example
Create a file my_script.py:
from forcepy import Salesforce
# Production org (default)
sf = Salesforce(
username='user@example.com',
password='password'
)
# With security token (if required)
sf = Salesforce(
username='user@example.com',
password='password',
security_token='yourSecurityToken123'
)
# Sandbox org
sf = Salesforce(
username='user@example.com',
password='password',
sandbox=True
)
# Query data with dot notation
accounts = sf.query("SELECT Id, Name, Industry FROM Account LIMIT 5")
for account in accounts.records:
print(f"{account.Name} - {account.Industry}")
Run it:
python my_script.py
That's it! You're already querying Salesforce data. ๐
Get more power!
Forcepy comes packed with advanced features:
๐ Advanced Query Building
from forcepy import Q
# Build complex queries with Q objects
high_value = Q(AnnualRevenue__gt=1000000) | Q(NumberOfEmployees__gt=500)
tech_companies = Q(Industry='Technology') & high_value
accounts = sf.query(f"SELECT Id, Name FROM Account WHERE {tech_companies.compile()}")
๐๏ธ Client-Side Filtering
# Query once, filter many times
cases = sf.query("SELECT Id, Status, Priority FROM Case LIMIT 1000")
# Filter client-side
urgent = cases.records.filter(Priority='High', Status='New')
# Group and aggregate
by_status = cases.records.group_by('Status').count()
# {'New': 450, 'In Progress': 300, 'Closed': 250}
โ๏ธ Composite API (Batch Operations)
# Execute up to 25 operations in a single API call
with sf as batch:
batch.sobjects.Account.post(Name='Acme Corp', Industry='Technology')
batch.sobjects.Account.post(Name='Global Inc', Industry='Finance')
batch.sobjects.Contact['003xx000004TmiQQAS'].patch(LastName='Smith')
# All operations execute atomically on exit
๐ฌ Chatter Integration
from forcepy import Chatter
chatter = Chatter(sf)
# Post with mentions and formatting
chatter.post("Hey @[005xx0000012345]! Check this out: <b>Q4 goals achieved!</b>")
# Post to groups
chatter.post_to_group("0F9xx000000abcd", "Team meeting at 2pm!")
๐ Developer Experience Features
# Convenience methods - cleaner code
accounts = sf.query("SELECT Id, Name FROM Account LIMIT 10")
first = accounts.records.first() # Instead of [0]
last = accounts.records.last() # Instead of [-1]
# Case-insensitive filtering - more flexible
cases = sf.query("SELECT Id, Subject, Status FROM Case")
urgent = cases.records.filter(Subject__icontains='urgent') # Matches "URGENT", "Urgent", etc.
new_cases = cases.records.filter(Status__iexact='new') # Case-insensitive exact match
# CSV export/import - easy data exchange
accounts.records.to_csv('accounts.csv')
from forcepy.results import ResultSet
imported = ResultSet.from_csv('accounts.csv')
๐๏ธ Bulk API 2.0
# Handle millions of records efficiently
records = [{'Name': f'Account {i}', 'Industry': 'Technology'} for i in range(10000)]
job = sf.bulk.Account.insert(records)
# Wait for completion and get results
results = job.wait()
print(f"Processed: {results['numberRecordsProcessed']}")
print(f"Failed: {results['numberRecordsFailed']}")
# Or query large datasets
job = sf.bulk.Account.query("SELECT Id, Name FROM Account")
for batch in job.get_results():
for record in batch:
print(record['Name'])
Key Features
๐ฏ Query & Filtering
- Q Objects - Build complex WHERE clauses with boolean logic
- Query helpers - IN(), DATE(), BOOL() for clean SOQL
- SELECT * expansion - Automatically expand to all fields
- Client-side filtering - filter(), group_by(), order_by() on results
- Iterquery - Efficient pagination with optional threading
๐ Authentication & Security
- SOAP login - Username/password authentication (auto-detects sandbox)
- JWT Bearer Flow - Certificate-based authentication for production
- OAuth2 - Full OAuth2 support
- Token caching - Automatic caching (memory/Redis) for performance
- Session tracking - Monitor user_id, session expiry, last request time
โก Performance & Reliability
- Auto-retry - Configurable retries on 503, 502, 500, UNABLE_TO_LOCK_ROW, 429
- Connection pooling - Efficient HTTP session management
- Smart caching - Describe/metadata results cached automatically
- Manual pagination - Full control with query_more() and next_records_url
๐ ๏ธ Developer Experience
- Full type hints - Better IDE autocomplete and type checking
- Dot notation - Access nested fields intuitively
- Dynamic endpoints - Chain attributes to build API paths
- Workbench URLs - Generate shareable query links
- Pretty print - Format SOQL for readability
- Object discovery - List and explore Salesforce objects
- ID utilities - Compare 15/18 char IDs, determine object type from ID
- Convenience methods -
.first(),.last()for cleaner code - Case-insensitive filters -
__icontains,__iexactfor flexible searching - CSV export/import - Easy data exchange with
.to_csv()and.from_csv()
๐ฆ Batch Operations
- Composite API - Batch up to 25 operations with reference support
- Context manager - Pythonic
withstatement for batching - All-or-none - Atomic transactions option
๐ Metadata & Schema
- Cached describe - Fast metadata access with automatic caching
- Field information - Required fields, picklist values, field properties
- Dependent picklists - Filter picklist values by controlling field
- Org limits - Check API usage and limits
Get Inspired
Here's what you can build with forcepy:
๐ Data Migration
Migrate millions of records between orgs with bulk operations and smart error handling.
๐ค Automation & Integration
Build workflows that sync Salesforce with external systems - CRMs, ERPs, databases, and more.
๐ Analytics & Reporting
Extract Salesforce data for custom analytics, dashboards, and business intelligence.
๐งช Testing & CI/CD
Populate test orgs, validate deployments, and automate quality assurance.
๐ฑ Custom Applications
Build custom apps that extend Salesforce capabilities beyond the platform.
Documentation
- ๐ Token Caching Guide - Production caching strategies
- ๐ Authentication Guide - All auth methods explained
- ๐ฌ Chatter Features - Complete Chatter reference
- ๐ก Examples - 13 ready-to-run code examples (including bulk operations!)
Resources
- Documentation:
- Authentication Guide - All auth methods explained
- Token Caching Guide - Production caching strategies
- Chatter Features - Complete Chatter reference
- Bulk API Guide - Handle large-scale operations
- Library Comparison - vs simple-salesforce
- Examples: 13 ready-to-run code examples
- Basic queries and CRUD operations
- Advanced filtering with Q objects
- Bulk API 2.0 for large-scale operations
- JWT and OAuth authentication
- Chatter integration
- Composite API batch operations
- Token caching strategies
- And more!
- Issues: Report bugs or request features
- Discussions: Get help from the community
Comparison with simple-salesforce
Forcepy builds on the foundation of simple-salesforce with many powerful additions:
| Feature | forcepy | simple-salesforce |
|---|---|---|
| Q Objects for complex queries | โ | โ |
| Query building helpers | โ | โ |
| Client-side filtering/grouping | โ | โ |
| JWT authentication | โ | โ |
| Token caching (automatic) | โ | โ |
| Redis cache support | โ | โ |
| Composite API | โ | โ |
| Dependent picklists | โ | โ |
| SELECT * expansion | โ | โ |
| Workbench URL generation | โ | โ |
| ID comparison utilities | โ | โ |
| Auto-retry on errors | โ | โ |
| Threaded iterquery | โ | โ |
| Session info properties | โ | โ |
| Composite context manager | โ | โ |
| Chatter integration | โ | Limited |
| Type hints | โ | Limited |
| Dot notation | โ | โ |
| SOQL queries | โ | โ |
| Bulk API 2.0 | โ | โ |
Examples
Basic Operations
from forcepy import Salesforce
sf = Salesforce(username='user@example.com', password='password')
# Create
result = sf.sobjects.Account.post(Name='Acme Corp', Industry='Technology')
account_id = result['id']
# Read
account = sf.sobjects.Account[account_id].get()
print(account['Name'])
# Update
sf.sobjects.Account[account_id].patch(Industry='Manufacturing')
# Delete
sf.sobjects.Account[account_id].delete()
Advanced Query with Q Objects
from forcepy import Q
# Complex boolean logic
tech_or_finance = Q(Industry='Technology') | Q(Industry='Finance')
high_revenue = Q(AnnualRevenue__gte=1000000)
california = Q(BillingState='CA')
query = tech_or_finance & high_revenue & california
accounts = sf.query(f"SELECT Id, Name FROM Account WHERE {query.compile()}")
Client-Side Data Manipulation
# Query all opportunities
opps = sf.query("SELECT Id, Name, Amount, StageName FROM Opportunity LIMIT 1000")
# Filter to closed-won
won = opps.records.filter(StageName='Closed Won')
# Group by stage and sum amounts
pipeline = opps.records.group_by('StageName').count()
# Sort by amount
top_deals = won.order_by('Amount', asc=False)[:10]
# Extract field values
amounts = opps.records.values_list('Amount', flat=True)
total = sum(amounts)
JWT Authentication (Production)
sf = Salesforce()
sf.login_with_jwt(
client_id='your-connected-app-id',
private_key='/path/to/private.key',
username='user@example.com'
)
Token Caching for Performance
# Redis cache for Kubernetes/multi-pod deployments
sf = Salesforce(
username='user@example.com',
password='password',
cache_backend='redis',
redis_url='redis://redis-service:6379'
)
# Second authentication reuses cached token - no API call!
Object Discovery (Perfect for Beginners!)
# List all custom objects
custom = sf.list_objects(custom_only=True)
for obj in custom:
print(f"{obj['name']}: {obj['label']}")
# Find what object a record ID belongs to
obj_type = sf.get_object_type_from_id('006xx0000012345')
print(f"This is a {obj_type} record")
Metadata & Describe
# Get object metadata (cached)
describe = sf.describe('Account')
# Required fields
for field in describe.required_fields:
print(field['name'])
# Picklist values
industries = describe.get_picklist_values('Industry')
# Dependent picklists
subcategories = describe.get_dependent_picklist_values(
field_name='Sub_Category__c',
controlling_value='Hardware'
)
Contributing
We welcome contributions! Here's how you can help:
- Report bugs - Open an issue with details and reproduction steps
- Suggest features - Share your ideas for improvements
- Submit PRs - See CONTRIBUTING.md for guidelines
- Improve docs - Help make our documentation better
- Share examples - Contribute real-world usage examples
Development
# Clone repository
git clone https://github.com/sanjan/forcepy.git
cd forcepy
# Install just (modern task runner)
brew install just # Mac
cargo install just # Any platform with Rust
# See docs/INSTALLING_JUST.md for other platforms
# Install dependencies
just install-dev
# Run tests
just test
# Run tests with coverage
just test-cov
# Lint and format
just format
just lint
# Run all quality checks
just quality
# Build package
just build
# See all commands
just --list
Without just: You can also use uv run directly:
uv sync --all-extras
uv run pytest
uv run ruff check src/ tests/
uv run mypy src/forcepy/
License
MIT License - see LICENSE file for details.
Support
- ๐ Bug reports: GitHub Issues
- ๐ฌ Questions: GitHub Discussions
- ๐ง Email: sgrero@salesforce.com
Made with โค๏ธ by developers, for developers.
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
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file forcepy-0.1.1.tar.gz.
File metadata
- Download URL: forcepy-0.1.1.tar.gz
- Upload date:
- Size: 117.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
b35ce660ffb5091a5c0cc8a85aa35c34196e8d60b9b024457ce1c9a5951c1f56
|
|
| MD5 |
6f4a2d758a7930092d70cf9e703b5a25
|
|
| BLAKE2b-256 |
a6a1b07fea8cb2c8a4e21262e7b4f9ab473bb7a2ce1af84ae175db7e196a5097
|
File details
Details for the file forcepy-0.1.1-py3-none-any.whl.
File metadata
- Download URL: forcepy-0.1.1-py3-none-any.whl
- Upload date:
- Size: 52.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
e1d58359bc858176524e5fd66eb63100e983bdbd012f6d3752f5c75eac406bd1
|
|
| MD5 |
c6101657466e3ccc603da8f812a47236
|
|
| BLAKE2b-256 |
693559f15433187012de4667ee298a01d00a4f675f92ed4abd39cea338c770ab
|