Sub topic 3
Upserting with an External ID with Bulk API 2.0
Assume you know Salesforce objects, external ID fields, REST methods, JSON, and CSV. An upsert updates a record when a matching external ID exists; otherwise, it creates a record.
Upserting with an external ID
Create an ingest job with operation set to upsert and identify the external ID field. Include that field in every CSV row.
curl -X POST "$INSTANCE_URL/services/data/v62.0/jobs/ingest" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"object":"Account","operation":"upsert","externalIdFieldName":"CustomerNumber__c","contentType":"CSV","lineEnding":"LF"}'The external ID must be unique. Duplicate matches can fail records instead of updating them predictably.
Handling failures and resubmitting records
After processing, retrieve failed rows. The response includes Salesforce error text and the source row’s ID information.
curl "$INSTANCE_URL/services/data/v62.0/jobs/ingest/$JOB_ID/failedResults/" \
-H "Authorization: Bearer $ACCESS_TOKEN"Fix only the failed rows and submit them in a new job. Also inspect unprocessed records when a job stops before Salesforce handles every row.
Exporting and paging with bulk query jobs
A bulk query job exports large result sets asynchronously.
curl -X POST "$INSTANCE_URL/services/data/v62.0/jobs/query" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"operation":"query","query":"SELECT Id, Name FROM Account"}'Poll until state is JobComplete, then request results. Salesforce returns a Sforce-Locator header when more pages exist. Pass that value as locator to fetch the next page.
| Result condition | Action |
|---|---|
| `Sforce-Locator: null` | The final page was returned. |
Limits and performance
Bulk API 2.0 batches an uploaded file internally. You manage jobs, not individual server batches. Respect file-size, API-request, and concurrent-job limits for your org.
Reduce lock contention by ordering related records consistently, avoiding many simultaneous jobs that touch the same parents, and retrying transient failures with backoff.
Putting it together
A script should create the job, upload the file, close the upload, poll terminal states, and save failures for review. Keep tokens in environment variables and log the job ID with each run.
Exercise
Which field lets an upsert identify an existing Salesforce record?
Show answer
A unique external ID field named in the job’s externalIdFieldName property.