Sub topic 6
Uploading the Data
This chapter covers the step between creating an ingest job and closing it: sending the CSV to Salesforce. It assumes you can already create an ingest job (the previous chapter), that you have a valid OAuth access token, and that you are comfortable with HTTP methods and CSV. The call looks simple, but several errors come from the upload step. They are wrong content types, line endings that don't match the job, and uploading to a job that is no longer open.
What the upload step does
After you create an ingest job, it is in the Open state. In this state Salesforce accepts data for the job but does not process it. You send the data with a single PUT request to the job's batches endpoint. Salesforce stores the data and waits. Processing begins only after you close the job, which is the next chapter's topic.
The endpoint has this form:
PUT /services/data/v62.0/jobs/ingest/{jobId}/batchesUse a current API version in place of v62.0. The request body is the raw CSV. You do not wrap it in JSON, and you do not split it into "batches" yourself. The word batches in the URL is a historical name. Bulk API 2.0 decides how to split the data internally, as the limits chapter explains.
The request
Three things must be correct in the upload request.
- The method is
PUT. APOSTto this URL is rejected. - The
Content-Typeheader istext/csv. This is not the same as thecontentTypefield in the job definition, which isCSV. The job field describes the format. The header describes this HTTP request. - The
Authorizationheader carries the same bearer token you used to create the job.
Here is the request with curl, using the CSV from the earlier chapter:
curl -X PUT "$INSTANCE_URL/services/data/v62.0/jobs/ingest/$JOB_ID/batches" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: text/csv" \
--data-binary @contacts.csvA successful upload returns HTTP status 201 Created with an empty body. There is no record count and no validation result in the response. Salesforce has only stored the bytes at this point. It checks the contents when it processes the job.
Why `--data-binary`
curl has two similar options, and the difference matters here. -d @file strips carriage returns and newlines from the file before sending it. That collapses a multi-row CSV into one line and corrupts it. --data-binary @file sends the file exactly as it is on disk. Always use --data-binary for CSV uploads.
Line endings must match the job
When you created the job you set lineEnding to LF or CRLF. The default on most platforms is LF. The upload must use the same line ending. If your file was saved on Windows, it probably uses CRLF, and uploading it to a job created with LF leaves a stray carriage return (\r) at the end of each line. That character becomes part of the last field's value. The effects are subtle: the last column of every row may fail validation, or a value may be saved with an invisible trailing character.
You have two options:
- Normalize the file to the line ending you declared when creating the job.
- Declare
CRLFin the job definition to match the file.
You can check what a file contains with a quick command:
file contacts.csvIf the output includes "with CRLF line terminators", the file uses Windows line endings.
Uploading from Python
The following script uploads a file using the requests library. It streams the file from disk, so it does not read the whole file into memory.
import os
import requests
instance = os.environ["SF_INSTANCE_URL"]
token = os.environ["SF_ACCESS_TOKEN"]
job_id = os.environ["SF_JOB_ID"]
url = f"{instance}/services/data/v62.0/jobs/ingest/{job_id}/batches"
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "text/csv",
}
with open("contacts.csv", "rb") as f:
resp = requests.put(url, headers=headers, data=f)
print(resp.status_code)
resp.raise_for_status()Open the file in binary mode ("rb"). Text mode can translate line endings on some platforms, which brings back the mismatch described above. When data is a file object, requests streams it from disk. The status should be 201.
One upload per job
A job accepts one upload. After you send the data and the request succeeds, you move on to closing the job. If you send a second PUT to the same job, Salesforce does not append the new data. Expect an error, and do not rely on the exact behavior. To load more data, create another job.
This shapes how you design large loads:
- Put all the records for one job in a single file, up to the size limit.
- If you have more data than the limit allows, split it across several jobs and run them one after another, or in parallel only when the records cannot lock each other (see the performance chapter).
- Do not try to use many
PUTcalls to build up one job.
Size limits for one upload
A single upload has a size cap. At the time of writing, the documented limit is 150 MB of base64-encoded data per upload. Base64 encoding makes data about one third larger, so the raw CSV limit you can rely on is lower than 150 MB. As a safe rule, keep each file under roughly 100 MB before encoding and check the current Salesforce documentation for your API version. Daily limits on records and job counts also apply, and the limits chapter covers them.
If a file is too large, split it by rows, not by bytes. Each part needs its own copy of the header row. The following script splits a large CSV into parts with a fixed number of data rows each. Each part keeps the header:
import csv
def split_csv(path, rows_per_file, prefix="part"):
names = []
with open(path, newline="", encoding="utf-8") as src:
reader = csv.reader(src)
header = next(reader)
out = None
writer = None
count = 0
index = 0
for row in reader:
if out is None or count == rows_per_file:
if out:
out.close()
index += 1
name = f"{prefix}_{index}.csv"
names.append(name)
out = open(name, "w", newline="", encoding="utf-8")
writer = csv.writer(out, lineterminator="\n")
writer.writerow(header)
count = 0
writer.writerow(row)
count += 1
if out:
out.close()
return names
print(split_csv("contacts.csv", 100000))Using the csv module keeps quoted fields that contain commas or line breaks intact. A plain split on newline characters would cut such records in half. The lineterminator="\n" argument writes LF endings, which match a job created with lineEnding set to LF.
Encoding
Send the file as UTF-8. Salesforce expects UTF-8 for CSV uploads. If you export from a spreadsheet, check that names with accents or non-Latin characters survive. A file saved in a legacy encoding will load without an upload error, but the saved values will be wrong. You will find the damage only after the job finishes.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `415 Unsupported Media Type` or a content error | `Content-Type` is not `text/csv` | Set the header to `text/csv` |
| `404 Not Found` | Wrong job ID, wrong instance URL, or wrong API version in the path | Check `$JOB_ID` and `$INSTANCE_URL` |
| `401 Unauthorized` | Expired or invalid access token | Get a new token and retry |
| Error saying the job is not in a state that accepts data | The job is already closed, aborted, or failed | Create a new job |
| Last column holds bad values after processing | Line ending in the file does not match `lineEnding` | Make them match |
| Whole file fails with a header error | Header names are not valid field API names | Fix the header row |
| Request rejected for size | File exceeds the per-upload limit | Split into several jobs |
Header problems usually appear after the job is closed and processed, not during the upload. Because the upload response says nothing about content, check your header row before you send it. You can do this cheaply: read the first line of the file and compare each name against the object's field list from the describe call.
Retrying a failed upload
If the PUT fails because of a network error or a timeout, you can't know whether Salesforce stored the data. The job is still Open, so check the job with a GET on /jobs/ingest/{jobId}. If it is Open, retry the PUT once. If a retry reports that data already exists, or if you are unsure, abort the job and start again with a new one. Starting over is safe because nothing is processed before you send UploadComplete.
An Open job that you never close does not run forever. Salesforce deletes jobs that stay unused after a retention period, but do not depend on this. Abort jobs you abandon by sending a PATCH with {"state":"Aborted"}.
Exercise
A colleague uploads a CSV to an ingest job created with "lineEnding":"LF". The upload returns 201, but after processing, every Contact's Email value ends with an invisible character and validation fails. The file was saved on Windows. What is the cause, and what are two ways to fix it?
Show answer
The file uses CRLF line endings, but the job declared LF. The carriage return at the end of each line becomes part of the last field's value. Fix it by converting the file to LF line endings and uploading it to a new job, or by creating a new job with "lineEnding":"CRLF" and uploading the file as it is. The old job cannot take the corrected data, so create a new job in either case.
Exercise
Why is curl -d @contacts.csv the wrong way to upload data, and what should you use instead?
Show answer
The -d option strips carriage returns and newlines from the file, so the CSV is sent as a single damaged line. Use --data-binary @contacts.csv, which sends the bytes exactly as stored.
Exercise
You have a 400 MB CSV. How should you load it with Bulk API 2.0?
Show answer
Split the file by rows into parts that are safely under the per-upload size limit, and repeat the header row in each part. Create one ingest job per part, upload each part with its own PUT, and close each job. Run the jobs one after another unless you are sure the records do not lock each other.