Sub topic 4
Preparing your CSV file
This chapter covers how to build a CSV file that Bulk API 2.0 accepts without errors. It assumes you know Salesforce field API names, external ID fields, and what a CSV file looks like. You should also know that an ingest job is created with a JSON request, as the earlier chapters on the job model showed. Here the focus is the file itself. Most failed loads come from data that doesn't match what the job declared, not from the API calls.
What Salesforce expects from the file
An ingest job reads one CSV payload. The payload follows a few fixed rules:
- The first row is a header. Each header cell is a field API name, such as
FirstNameorCustom_Field__c. Labels like "First Name" are not accepted. - Every following row is one record.
- Column order does not matter. The header names decide which value goes to which field.
- Every row must have the same number of columns as the header.
- The file must be UTF-8 text.
- Every header must be a field on the target object that you can write to. An unknown or read-only field causes an error.
The job settings you send when you create the job must match the file. Two settings matter most: lineEnding (LF or CRLF) and columnDelimiter. The delimiter defaults to COMMA. Other allowed values are BACKQUOTE, CARET, PIPE, SEMICOLON, and TAB.
Required columns by operation
Which columns you need depends on the operation you chose when creating the job.
| Operation | Required columns | Notes |
|---|---|---|
| `insert` | Every field that the object requires | For example, `LastName` for Contact |
| `update` | `Id`, plus the fields to change | Columns you leave out are not touched |
| `upsert` | The external ID field, plus the fields to set | Covered in the upsert chapter |
| `delete` and `hardDelete` | `Id` only | Extra columns are not needed |
Extra columns are a common mistake. A file exported from a spreadsheet or another system often has columns that are not Salesforce fields. Remove them, or the job fails.
Quoting and special characters
CSV needs quoting when a value contains the delimiter, a double quote, or a line break. The rules are the standard ones:
- Wrap the whole value in double quotes.
- Write each double quote inside the value as two double quotes (
""). - A quoted value may contain line breaks. Those breaks are part of the value and are kept as written.
For example, this record has a comma and a quote in the description and a line break inside it:
LastName,Description
Lovelace,"Wrote notes on the ""Analytical Engine"",
then published them."Don't build these lines with string concatenation. Use a CSV library, which applies the rules the same way every time.
Empty values and setting a field to null
An empty cell does not clear a field. Bulk API 2.0 treats an empty value as "no change", so an update leaves the existing data alone. To set a field to null, write #N/A in that cell.
| Cell content | Effect on the field |
|---|---|
| (empty) | Not changed |
| `#N/A` | Set to null |
| `Ada` | Set to `Ada` |
Use #N/A only for fields that can hold null. A required field rejects it, and that row fails.
Formats for dates, times and other types
Salesforce parses text according to the field type. Wrong formats are the second most common cause of failed rows.
| Field type | Format | Example |
|---|---|---|
| Date | `yyyy-MM-dd` | `1815-12-10` |
| Date/Time | ISO 8601 with a time zone | `2026-12-01T09:00:00.000Z` |
| Boolean | `true` or `false` | `true` |
| Number, currency, percent | Plain digits with `.` as the decimal point, no thousands separators | `1234.50` |
| Picklist | The exact picklist value | `Prospect` |
For Date/Time values, include the zone: either Z for UTC or an offset such as +01:00. Without it, the meaning of the time is ambiguous. Spreadsheets often reformat dates when they save a file, so check the saved result in a text editor, not in the spreadsheet.
Referencing related records
A lookup field normally holds a record ID, for example AccountId. If you only know the parent's external ID, you can use a relationship column instead. The header has the form RelationshipName.ExternalIdField:
FirstName,LastName,Account.Legacy_Id__c
Ada,Lovelace,ACME-001
Alan,Turing,ACME-002Here Account is the relationship name on Contact, and Legacy_Id__c is an external ID field on Account. For a custom relationship, use the relationship name that ends in __r, such as Region__r.Code__c. The parent records must already exist. A value that matches no parent fails that row.
File size and when to split
A single job accepts a limited amount of data per upload. At the time of writing the limit is 150 MB per job, and Salesforce counts the data after it is encoded for transfer. Because that encoding makes the data larger, keep your raw file comfortably below the limit. Salesforce also caps the number of records you can process per rolling 24 hours, and this cap changes by edition and over time. Check the current limits before planning a very large load. A later chapter explains how Salesforce divides the data into batches. You only need to decide whether one file fits in one job. If it does not, split it into several files, and keep the header row in each file.
Generating and checking a file with Python
The script below writes a CSV with the standard library, then checks it against the rules in this chapter. It uses \n line endings, which matches "lineEnding":"LF" on the job.
import csv
FIELDS = ["FirstName", "LastName", "Email", "Birthdate", "Description"]
rows = [
{
"FirstName": "Ada",
"LastName": "Lovelace",
"Email": "[email protected]",
"Birthdate": "1815-12-10",
"Description": 'Wrote notes on the "Analytical Engine", then published them.',
},
{
"FirstName": "Alan",
"LastName": "Turing",
"Email": "[email protected]",
"Birthdate": "#N/A", # set Birthdate to null
"Description": "", # leave Description unchanged
},
]
with open("contacts.csv", "w", encoding="utf-8", newline="") as f:
writer = csv.DictWriter(f, fieldnames=FIELDS, lineterminator="\n")
writer.writeheader()
writer.writerows(rows)
def check(path, allowed_fields):
with open(path, "rb") as f:
raw = f.read()
problems = []
if b"\r\n" in raw:
problems.append("file contains CRLF line endings")
text = raw.decode("utf-8") # raises an error if the file is not UTF-8
reader = csv.reader(text.splitlines(keepends=True))
header = next(reader)
for name in header:
if name not in allowed_fields:
problems.append(f"unknown header: {name}")
for number, row in enumerate(reader, start=2):
if len(row) != len(header):
problems.append(f"record {number}: {len(row)} columns, expected {len(header)}")
return problems
print(check("contacts.csv", set(FIELDS)) or "file looks valid")The check is a local guard. It cannot know your org's schema, so allowed_fields here is just the list you wrote. For a stricter check, build that set from the object's field describe, which lists each field and whether it is writable.
Common errors
- Spreadsheet damage. Excel can strip leading zeros, turn long numbers into scientific notation, and rewrite dates. Export from a script or a database where you can, or open the saved file in a text editor and verify it.
- Byte order mark. Some tools add an invisible marker at the start of a UTF-8 file. It can attach itself to the first header name and make it unrecognizable. Save as "UTF-8" without a BOM.
- Wrong delimiter. A European-locale spreadsheet may save with semicolons. Either convert the file to commas or set
columnDelimitertoSEMICOLONon the job. - Trailing blank lines or short rows. A row with fewer columns than the header fails. Remove empty rows at the end of the file.
- Header typos.
FirstnameandFirstNamemay look alike to a person, but check names against the object's field list.
Exercise
A CSV for an update job has the header Id,Phone,Fax. For one record you want to erase the existing Fax value and keep the Phone value as it is. What do you put in the Phone and Fax cells of that row?
Show answer
Leave the Phone cell empty, because an empty cell means "no change", and write #N/A in the Fax cell, because #N/A sets a field to null. Writing the old Phone value again would also work but is not needed.
Exercise
You export Contact data from another system. The file has CRLF line endings, a column called "Customer Notes", and dates written as 12/10/1815. Name the three changes you need to make before creating an insert job with "lineEnding":"LF".
Show answer
First, either convert the file to LF line endings or create the job with lineEnding set to CRLF. Second, rename or remove the "Customer Notes" column so the header is a valid field API name, such as Description or a custom field ending in __c. Third, rewrite the dates in yyyy-MM-dd form, for example 1815-12-10.