or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

authentication.mdbulk-operations.mdbulk2-operations.mdexceptions.mdindex.mdmetadata-api.mdrest-api.mdutilities.md

rest-api.mddocs/

0

# REST API Operations

1

2

Core Salesforce class and SFType interface providing complete CRUD operations, queries, searches, and metadata access for Salesforce objects through the REST API. These components form the foundation for all standard Salesforce interactions.

3

4

## Core Salesforce Class

5

6

The primary client class managing authentication, session state, and providing access to all Salesforce REST API endpoints.

7

8

```python { .api }

9

class Salesforce:

10

def __init__(

11

self,

12

username=None,

13

password=None,

14

security_token=None,

15

session_id=None,

16

instance=None,

17

instance_url=None,

18

organizationId=None,

19

version="59.0",

20

proxies=None,

21

session=None,

22

client_id=None,

23

domain=None,

24

consumer_key=None,

25

consumer_secret=None,

26

privatekey_file=None,

27

privatekey=None,

28

parse_float=None,

29

object_pairs_hook=dict

30

):

31

"""

32

Initialize Salesforce REST API client.

33

34

Parameters:

35

- Authentication parameters: See authentication.md for details

36

- version: Salesforce API version (default: "59.0")

37

- proxies: HTTP proxy configuration dictionary

38

- session: Custom requests.Session object

39

- parse_float: Custom JSON float parser function

40

- object_pairs_hook: JSON object parsing hook (default: dict)

41

"""

42

```

43

44

## Key Properties

45

46

Session and endpoint information available after successful authentication:

47

48

```python { .api }

49

class Salesforce:

50

@property

51

def session_id(self) -> str:

52

"""Current Salesforce session ID"""

53

54

@property

55

def sf_instance(self) -> str:

56

"""Salesforce instance domain (e.g., 'na1.salesforce.com')"""

57

58

@property

59

def sf_version(self) -> str:

60

"""API version in use"""

61

62

@property

63

def base_url(self) -> str:

64

"""Base REST API URL"""

65

66

@property

67

def bulk_url(self) -> str:

68

"""Bulk API v1.0 URL"""

69

70

@property

71

def bulk2_url(self) -> str:

72

"""Bulk API v2.0 URL"""

73

74

@property

75

def metadata_url(self) -> str:

76

"""Metadata API URL"""

77

78

@property

79

def tooling_url(self) -> str:

80

"""Tooling API URL"""

81

82

@property

83

def oauth2_url(self) -> str:

84

"""OAuth 2.0 API URL"""

85

86

@property

87

def api_usage(self) -> dict:

88

"""API usage statistics from last request"""

89

90

@property

91

def mdapi(self):

92

"""Metadata API interface (SfdcMetadataApi instance)"""

93

```

94

95

## Query Operations

96

97

SOQL query execution with support for large result sets and deleted records.

98

99

```python { .api }

100

class Salesforce:

101

def query(self, query, include_deleted=False, **kwargs):

102

"""

103

Execute SOQL query and return results.

104

105

Parameters:

106

- query: SOQL query string

107

- include_deleted: Include deleted/archived records

108

- **kwargs: Additional request parameters (headers, etc.)

109

110

Returns:

111

dict: Query results with 'records', 'totalSize', 'done', and 'nextRecordsUrl'

112

"""

113

114

def query_more(self, next_records_identifier, identifier_is_url=False, include_deleted=False, **kwargs):

115

"""

116

Retrieve additional query results using nextRecordsUrl or identifier.

117

118

Parameters:

119

- next_records_identifier: Next records URL or identifier

120

- identifier_is_url: True if identifier is complete URL

121

- include_deleted: Include deleted/archived records

122

- **kwargs: Additional request parameters

123

124

Returns:

125

dict: Additional query results

126

"""

127

128

def query_all(self, query, include_deleted=False, **kwargs):

129

"""

130

Execute query and automatically retrieve all results.

131

132

Parameters:

133

- query: SOQL query string

134

- include_deleted: Include deleted/archived records

135

- **kwargs: Additional request parameters

136

137

Returns:

138

dict: Complete query results with all records

139

"""

140

141

def query_all_iter(self, query, include_deleted=False, **kwargs):

142

"""

143

Lazy iterator for query results, yielding records as retrieved.

144

145

Parameters:

146

- query: SOQL query string

147

- include_deleted: Include deleted/archived records

148

- **kwargs: Additional request parameters

149

150

Yields:

151

dict: Individual record dictionaries

152

"""

153

```

154

155

### Query Usage Examples

156

157

```python

158

from simple_salesforce import Salesforce

159

160

sf = Salesforce(username='user@example.com', password='pass', security_token='token')

161

162

# Basic query

163

results = sf.query("SELECT Id, Name FROM Account LIMIT 10")

164

for record in results['records']:

165

print(f"Account: {record['Name']}")

166

167

# Query with deleted records

168

deleted_results = sf.query(

169

"SELECT Id, Name FROM Account WHERE IsDeleted = true",

170

include_deleted=True

171

)

172

173

# Large result set with pagination

174

all_results = sf.query_all("SELECT Id, Name FROM Account")

175

print(f"Total accounts: {all_results['totalSize']}")

176

177

# Memory-efficient iteration over large results

178

for record in sf.query_all_iter("SELECT Id, Name FROM Account"):

179

process_account(record)

180

```

181

182

## Search Operations

183

184

SOSL search functionality for cross-object text searching.

185

186

```python { .api }

187

class Salesforce:

188

def search(self, search):

189

"""

190

Execute SOSL search with complete search string.

191

192

Parameters:

193

- search: Complete SOSL search string including FIND clause

194

195

Returns:

196

list: Search results grouped by object type

197

"""

198

199

def quick_search(self, search):

200

"""

201

Execute simplified SOSL search (auto-wraps in FIND clause).

202

203

Parameters:

204

- search: Search terms (automatically wrapped in FIND{})

205

206

Returns:

207

list: Search results grouped by object type

208

"""

209

```

210

211

### Search Usage Examples

212

213

```python

214

# Full SOSL search

215

search_results = sf.search(

216

"FIND {test} IN ALL FIELDS RETURNING Account(Id, Name), Contact(Id, Name)"

217

)

218

219

# Quick search (simplified)

220

quick_results = sf.quick_search("test company")

221

222

# Process search results

223

for sobject_results in search_results:

224

print(f"Object type: {sobject_results['attributes']['type']}")

225

for record in sobject_results['records']:

226

print(f" {record['Name']}")

227

```

228

229

## Describe Operations

230

231

Metadata and schema information retrieval for objects and the organization.

232

233

```python { .api }

234

class Salesforce:

235

def describe(self, **kwargs):

236

"""

237

Describe all available Salesforce objects in the organization.

238

239

Parameters:

240

- **kwargs: Additional request parameters (headers, etc.)

241

242

Returns:

243

dict: Organization describe information with 'sobjects' list

244

"""

245

246

def is_sandbox(self):

247

"""

248

Check if the current organization is a sandbox.

249

250

Returns:

251

bool: True if sandbox, False if production

252

"""

253

```

254

255

### Describe Usage Examples

256

257

```python

258

# Get all available objects

259

org_describe = sf.describe()

260

for sobject in org_describe['sobjects']:

261

if sobject['createable']:

262

print(f"Createable object: {sobject['name']}")

263

264

# Check environment

265

if sf.is_sandbox():

266

print("Connected to sandbox environment")

267

else:

268

print("Connected to production environment")

269

```

270

271

## Direct REST Operations

272

273

Low-level REST API access for custom endpoints and advanced operations.

274

275

```python { .api }

276

class Salesforce:

277

def restful(self, path, params=None, method='GET', **kwargs):

278

"""

279

Make direct REST API calls to Salesforce endpoints.

280

281

Parameters:

282

- path: API endpoint path (relative to base URL)

283

- params: Query parameters dictionary

284

- method: HTTP method (GET, POST, PUT, PATCH, DELETE)

285

- **kwargs: Additional request parameters (data, headers, etc.)

286

287

Returns:

288

requests.Response: Raw HTTP response object

289

"""

290

291

def oauth2(self, path, params=None, method='GET'):

292

"""

293

Make calls to OAuth 2.0 API endpoints.

294

295

Parameters:

296

- path: OAuth endpoint path

297

- params: Query parameters dictionary

298

- method: HTTP method

299

300

Returns:

301

requests.Response: Raw HTTP response object

302

"""

303

```

304

305

### Direct REST Usage Examples

306

307

```python

308

# Custom REST endpoint

309

response = sf.restful('sobjects/Account/describe')

310

account_metadata = response.json()

311

312

# OAuth introspection

313

token_info = sf.oauth2('introspect', params={'token': sf.session_id})

314

315

# Custom API endpoint with POST

316

custom_response = sf.restful(

317

'sobjects/Account',

318

method='POST',

319

json={'Name': 'Test Account', 'Type': 'Customer'}

320

)

321

```

322

323

## Specialized API Operations

324

325

### Tooling and Apex APIs

326

327

```python { .api }

328

class Salesforce:

329

def toolingexecute(self, action, method='GET', data=None, **kwargs):

330

"""

331

Execute Tooling API operations for development tools.

332

333

Parameters:

334

- action: Tooling API endpoint path

335

- method: HTTP method

336

- data: Request body data

337

- **kwargs: Additional request parameters

338

339

Returns:

340

dict: Tooling API response

341

"""

342

343

def apexecute(self, action, method='GET', data=None, **kwargs):

344

"""

345

Execute Apex REST API operations for custom Apex endpoints.

346

347

Parameters:

348

- action: Apex REST endpoint path

349

- method: HTTP method

350

- data: Request body data

351

- **kwargs: Additional request parameters

352

353

Returns:

354

dict: Apex REST response

355

"""

356

```

357

358

### User Management

359

360

```python { .api }

361

class Salesforce:

362

def set_password(self, user, password):

363

"""

364

Set password for a Salesforce user.

365

366

Parameters:

367

- user: User ID (18-character Salesforce ID)

368

- password: New password string

369

370

Returns:

371

dict: Password reset response

372

"""

373

```

374

375

### Organization Information

376

377

```python { .api }

378

class Salesforce:

379

def limits(self, **kwargs):

380

"""

381

Get organization limits and usage information.

382

383

Parameters:

384

- **kwargs: Additional request parameters

385

386

Returns:

387

dict: Organization limits including API usage, storage, etc.

388

"""

389

```

390

391

## Dynamic SObject Access

392

393

The Salesforce class provides dynamic attribute access to create SFType instances for any Salesforce object.

394

395

```python

396

sf = Salesforce(username='user@example.com', password='pass', security_token='token')

397

398

# Access any standard or custom object

399

accounts = sf.Account # Returns SFType for Account

400

contacts = sf.Contact # Returns SFType for Contact

401

custom = sf.MyCustom__c # Returns SFType for custom object

402

403

# Access bulk handlers

404

bulk_v1 = sf.bulk # Returns SFBulkHandler

405

bulk_v2 = sf.bulk2 # Returns SFBulk2Handler

406

```

407

408

## SFType Class

409

410

Interface for operations on specific Salesforce SObject types, providing CRUD operations, metadata access, and specialized functionality.

411

412

```python { .api }

413

class SFType:

414

def __init__(

415

self,

416

object_name,

417

session_id,

418

sf_instance,

419

sf_version="59.0",

420

proxies=None,

421

session=None,

422

salesforce=None,

423

parse_float=None,

424

object_pairs_hook=dict

425

):

426

"""

427

Initialize SFType for specific Salesforce object.

428

429

Parameters:

430

- object_name: Salesforce object API name

431

- session_id: Authenticated session ID

432

- sf_instance: Salesforce instance URL

433

- sf_version: API version string

434

- proxies: HTTP proxy configuration

435

- session: Custom requests.Session object

436

- salesforce: Parent Salesforce instance

437

- parse_float: Custom JSON float parser

438

- object_pairs_hook: JSON object parsing hook

439

"""

440

```

441

442

### SFType Properties

443

444

```python { .api }

445

class SFType:

446

@property

447

def name(self) -> str:

448

"""SObject API name"""

449

450

@property

451

def session_id(self) -> str:

452

"""Session ID for authentication"""

453

454

@property

455

def base_url(self) -> str:

456

"""Base URL for this SObject type"""

457

458

@property

459

def api_usage(self) -> dict:

460

"""API usage statistics from last request"""

461

```

462

463

### CRUD Operations

464

465

Complete Create, Read, Update, Delete operations for Salesforce records.

466

467

```python { .api }

468

class SFType:

469

def create(self, data, headers=None):

470

"""

471

Create new record for this SObject type.

472

473

Parameters:

474

- data: Record field data dictionary

475

- headers: Optional HTTP headers

476

477

Returns:

478

dict: Created record information with 'id' and 'success'

479

"""

480

481

def get(self, record_id, headers=None, **kwargs):

482

"""

483

Get record by Salesforce ID.

484

485

Parameters:

486

- record_id: 15 or 18-character Salesforce record ID

487

- headers: Optional HTTP headers

488

- **kwargs: Additional query parameters

489

490

Returns:

491

dict: Complete record data

492

"""

493

494

def get_by_custom_id(self, custom_id_field, custom_id, headers=None, **kwargs):

495

"""

496

Get record by external/custom ID field.

497

498

Parameters:

499

- custom_id_field: External ID field API name

500

- custom_id: External ID value

501

- headers: Optional HTTP headers

502

- **kwargs: Additional query parameters

503

504

Returns:

505

dict: Complete record data

506

"""

507

508

def update(self, record_id, data, raw_response=False, headers=None):

509

"""

510

Update existing record.

511

512

Parameters:

513

- record_id: Salesforce record ID to update

514

- data: Updated field data dictionary

515

- raw_response: Return raw HTTP response if True

516

- headers: Optional HTTP headers

517

518

Returns:

519

int|dict: HTTP status code (204) or error details if raw_response=True

520

"""

521

522

def upsert(self, record_id, data, raw_response=False, headers=None):

523

"""

524

Create or update record (upsert operation).

525

526

Parameters:

527

- record_id: External ID value for upsert matching

528

- data: Record field data dictionary

529

- raw_response: Return raw HTTP response if True

530

- headers: Optional HTTP headers

531

532

Returns:

533

dict: Upsert result with 'id', 'success', and 'created' status

534

"""

535

536

def delete(self, record_id, raw_response=False, headers=None):

537

"""

538

Delete record (soft delete).

539

540

Parameters:

541

- record_id: Salesforce record ID to delete

542

- raw_response: Return raw HTTP response if True

543

- headers: Optional HTTP headers

544

545

Returns:

546

int|dict: HTTP status code (204) or error details if raw_response=True

547

"""

548

```

549

550

### Metadata Operations

551

552

Schema and metadata information for SObject types.

553

554

```python { .api }

555

class SFType:

556

def metadata(self, headers=None):

557

"""

558

Get SObject metadata information.

559

560

Parameters:

561

- headers: Optional HTTP headers

562

563

Returns:

564

dict: Complete SObject metadata

565

"""

566

567

def describe(self, headers=None):

568

"""

569

Get detailed SObject describe information including fields.

570

571

Parameters:

572

- headers: Optional HTTP headers

573

574

Returns:

575

dict: SObject describe with fields, record types, etc.

576

"""

577

578

def describe_layout(self, record_id, headers=None):

579

"""

580

Get layout information for a specific record.

581

582

Parameters:

583

- record_id: Record ID for layout context

584

- headers: Optional HTTP headers

585

586

Returns:

587

dict: Layout information for the record

588

"""

589

```

590

591

### Change Tracking

592

593

Track record changes over time periods for data synchronization.

594

595

```python { .api }

596

class SFType:

597

def updated(self, start, end, headers=None):

598

"""

599

Get list of updated records in date range.

600

601

Parameters:

602

- start: Start date (ISO format or datetime)

603

- end: End date (ISO format or datetime)

604

- headers: Optional HTTP headers

605

606

Returns:

607

dict: List of record IDs updated in the time period

608

"""

609

610

def deleted(self, start, end, headers=None):

611

"""

612

Get list of deleted records in date range.

613

614

Parameters:

615

- start: Start date (ISO format or datetime)

616

- end: End date (ISO format or datetime)

617

- headers: Optional HTTP headers

618

619

Returns:

620

dict: List of record IDs deleted in the time period

621

"""

622

```

623

624

### File Operations

625

626

Handle base64-encoded file uploads and downloads for file fields.

627

628

```python { .api }

629

class SFType:

630

def upload_base64(self, file_path, base64_field='Body', headers=None, **kwargs):

631

"""

632

Upload file as base64-encoded content to create new record.

633

634

Parameters:

635

- file_path: Path to local file for upload

636

- base64_field: Field name for base64 content (default: 'Body')

637

- headers: Optional HTTP headers

638

- **kwargs: Additional record field data

639

640

Returns:

641

dict: Created record information

642

"""

643

644

def update_base64(self, record_id, file_path, base64_field='Body', headers=None, raw_response=False, **kwargs):

645

"""

646

Update record with base64-encoded file content.

647

648

Parameters:

649

- record_id: Record ID to update

650

- file_path: Path to local file for upload

651

- base64_field: Field name for base64 content

652

- headers: Optional HTTP headers

653

- raw_response: Return raw HTTP response if True

654

- **kwargs: Additional field updates

655

656

Returns:

657

int|dict: HTTP status or response data

658

"""

659

660

def get_base64(self, record_id, base64_field='Body', data=None, headers=None, **kwargs):

661

"""

662

Get base64-encoded file content from record.

663

664

Parameters:

665

- record_id: Record ID containing file data

666

- base64_field: Field name containing base64 content

667

- data: Optional additional query data

668

- headers: Optional HTTP headers

669

- **kwargs: Additional query parameters

670

671

Returns:

672

dict: Record data including base64 file content

673

"""

674

```

675

676

### SFType Usage Examples

677

678

```python

679

from simple_salesforce import Salesforce

680

681

sf = Salesforce(username='user@example.com', password='pass', security_token='token')

682

683

# Get SFType for Account object

684

account_type = sf.Account

685

686

# Create new account

687

new_account = account_type.create({

688

'Name': 'Test Account',

689

'Type': 'Customer',

690

'Industry': 'Technology'

691

})

692

print(f"Created account ID: {new_account['id']}")

693

694

# Get account by ID

695

account = account_type.get(new_account['id'])

696

print(f"Account name: {account['Name']}")

697

698

# Update account

699

account_type.update(new_account['id'], {

700

'Phone': '555-123-4567',

701

'Website': 'https://example.com'

702

})

703

704

# Get account metadata

705

metadata = account_type.describe()

706

for field in metadata['fields']:

707

if field['type'] == 'email':

708

print(f"Email field: {field['name']}")

709

710

# Check for recent changes

711

from datetime import datetime, timedelta

712

end_date = datetime.now()

713

start_date = end_date - timedelta(days=7)

714

715

updated_records = account_type.updated(start_date, end_date)

716

print(f"Updated records: {updated_records}")

717

718

# File upload example (for Document or Attachment)

719

document_type = sf.Document

720

doc_result = document_type.upload_base64(

721

'/path/to/file.pdf',

722

Name='Important Document',

723

FolderId='00l000000000000' # Document folder ID

724

)

725

```

726

727

## Utility Methods

728

729

Helper functions for response processing and API usage analysis.

730

731

```python { .api }

732

class Salesforce:

733

def parse_result_to_json(self, result):

734

"""

735

Parse requests.Response object to JSON with error handling.

736

737

Parameters:

738

- result: requests.Response object

739

740

Returns:

741

dict: Parsed JSON response data

742

"""

743

744

@staticmethod

745

def parse_api_usage(sforce_limit_info):

746

"""

747

Parse Salesforce API usage information from response headers.

748

749

Parameters:

750

- sforce_limit_info: Sforce-Limit-Info header value

751

752

Returns:

753

dict: Parsed API usage statistics

754

"""

755

```