Step 5: Bulk Upsert
This Bulk API 2.0 example guides you through creating a job, uploading data for the job, notifying Salesforce servers that your upload(s) are complete, checking the status, and retrieving the results. Some of the records exist (update), and some are new records (insert).
-
Confirm that your object is using an external ID field.
Upserting records requires an external ID field on the object involved in the job. Bulk API 2.0 uses the external ID field to determine whether a record is used to update an existing record or create a record.
This example assumes that the external ID field
customExtIdField__chas been added to theAccountobject.To add this custom field in your org with Object Manager, use these properties.
- Data Type—text
- Field Label—customExtIdField
- Select External ID For more information, see Custom Fields in Salesforce Help.
-
Create a CSV file containing the records that you want to upsert.
Save all files in this example in your terminal’s current working directory.
The first row of the CSV file lists the field names for the object that you’re working with. Each subsequent row corresponds to a record that you want to insert.
One column in the CSV file must correspond to the external ID field
customExtIdField__c.For information on preparing CSV files, such as delimiter options and valid date and time formats, see Bulk API 2.0 Ingest.
For this example, copy this information into a file named
accountupsert.csv. -
Create a job that includes the external ID field.
Copy this information into a file named
newupsertjob.json.URI
Example for creating a bulk upsert job
Example response body
The response includes the job ID, with a job state of Open. Use the job ID and the URL in the contentUrl field in the next step when you upload your data.
-
Upload the CSV data file that you created.
URI
For convenience, use the URI in the
contentUrlfield of the response from step 1. The URI is similar to:Example for uploading data
Example response body
No response body is returned.
-
Set
statetoUploadComplete.After you’re done submitting data, notify Salesforce servers that the upload of job data is complete and is ready for processing.
Create a JSON file named upload_complete.json with the contents:
URI
/services/data/v68.0/jobs/ingest/jobId/
Example of setting
statetoUploadCompleteExample response body
-
Get successful results.
After a job is in the
JobCompleteorFailedstate, you can get details about which job data records were successfully processed.URI
Example of getting successful results
The response contains CSV formatted data, with each row containing a record ID of successfully processed records.
Example response body
To get details about records that encountered an error, use the
failedResultsresource. To make sure that you’re looking at the complete result set, use theunprocessedRecordsresource. See Get Job Unprocessed Record Results.