Sub topic 16
Putting it together in a script
This chapter combines the earlier steps into one Python script that loads a CSV file and saves the results. It assumes you have a valid OAuth access token, the requests library, and the job model from earlier chapters. The script runs from top to bottom with no manual steps.
The flow the script follows
Every ingest load follows the same sequence of calls. The script sends them in this order and stops when the job reaches a terminal state.
The script
Set SF_INSTANCE_URL and SF_ACCESS_TOKEN as environment variables first. Save the CSV from the preparation chapter as contacts.csv.
import os
import sys
import time
import requests
instance = os.environ["SF_INSTANCE_URL"]
token = os.environ["SF_ACCESS_TOKEN"]
base = f"{instance}/services/data/v62.0/jobs/ingest"
auth = {"Authorization": f"Bearer {token}"}
TERMINAL = ("JobComplete", "Failed", "Aborted")
def save(job_id, endpoint, filename):
resp = requests.get(f"{base}/{job_id}/{endpoint}/", headers=auth)
resp.raise_for_status()
with open(filename, "wb") as out:
out.write(resp.content)
job = requests.post(
base,
headers=auth,
json={"object": "Contact", "operation": "insert",
"contentType": "CSV", "lineEnding": "LF"},
)
job.raise_for_status()
job_id = job.json()["id"]
print("Created job", job_id)
with open("contacts.csv", "rb") as f:
requests.put(
f"{base}/{job_id}/batches",
headers={**auth, "Content-Type": "text/csv"},
data=f,
).raise_for_status()
requests.patch(
f"{base}/{job_id}", headers=auth, json={"state": "UploadComplete"}
).raise_for_status()
while True:
resp = requests.get(f"{base}/{job_id}", headers=auth)
resp.raise_for_status()
info = resp.json()
print("State:", info["state"])
if info["state"] in TERMINAL:
break
time.sleep(10)
print("Processed:", info.get("numberRecordsProcessed"),
"Failed:", info.get("numberRecordsFailed"))
save(job_id, "successfulResults", "success.csv")
save(job_id, "failedResults", "failed.csv")
save(job_id, "unprocessedrecords", "unprocessed.csv")
if info["state"] != "JobComplete" or info.get("numberRecordsFailed"):
sys.exit(1)How the script handles each stage
- Creation and upload. Each call uses
raise_for_status(), so a bad token or malformed request stops the script before it closes a broken job. - Streaming the file. Passing the open file object as
datasends the bytes as they are, so line endings stay as written. This must match thelineEndingvalue in the job request. - Polling. The loop checks the state every 10 seconds. Checking the three terminal states, not only
JobComplete, prevents an infinite loop when a job fails. - Results. The script saves all three result files. A
FailedorAbortedjob often leaves rows inunprocessed.csvthat were never attempted. - Exit code. A non-zero exit lets a scheduler or CI job detect a partial load.
Resubmitting failures
failed.csv starts with sf__Id and sf__Error columns, followed by your original columns. Before resubmitting, fix the cause named in sf__Error and remove those two columns. Then run the script again with the cleaned file as the input. Do the same with unprocessed.csv, which needs no data fixes because those rows were never tried.
Extending the script
Move the file name, object, and operation into command-line arguments. Add a maximum wait time to the polling loop. For an upsert, add "externalIdFieldName" to the job request body.
Exercise
The script exits with a non-zero code even though the job state is JobComplete. What is the likely cause, and which file do you read next?
Show answer
Some rows failed, so numberRecordsFailed is greater than zero. JobComplete means Salesforce finished processing, not that every row succeeded. Read failed.csv and check the sf__Error column for each row.