Sub topic 2
Authentication and endpoint structure
This chapter assumes you know what an OAuth 2.0 access token is and can send HTTP requests with curl or Python requests. It does not cover how to obtain a token in depth. It covers what Bulk API 2.0 needs from a token, how to build its URLs, and which headers each call requires.
What a request needs
Every Bulk API 2.0 call is an HTTPS request to your org's instance. Each request carries three things:
- A base URL that identifies your org: the instance URL.
- A path that names the API version and the job resource.
- An
Authorization: Bearerheader that holds the access token.
Bulk API 2.0 has no separate login. It uses the same OAuth tokens as the rest of the Salesforce REST API. A token that works for /services/data/v62.0/query also works for /services/data/v62.0/jobs/ingest, as long as the user has the right permissions.
Getting a token and an instance URL
The OAuth token response contains two values you need:
access_token: the credential you send in theAuthorizationheader.instance_url: the base URL for all API calls, for examplehttps://mycompany.my.salesforce.com.
Always use the instance_url you were given. Do not build it from login.salesforce.com. That host handles authentication, not data requests.
Which OAuth flow you use depends on how your loader runs:
| Situation | Typical flow |
|---|---|
| Scheduled job with no human present | JWT bearer flow or client credentials flow |
| Tool that acts for a signed-in user | Web server (authorization code) flow |
| Local development and testing | Salesforce CLI login |
For local work, the Salesforce CLI is the quickest route. After sf org login web, you can read a current token and instance URL from the CLI:
sf org display --target-org my-org --json > org.json
export INSTANCE_URL=$(jq -r '.result.instanceUrl' org.json)
export ACCESS_TOKEN=$(jq -r '.result.accessToken' org.json)The tutorial's later curl examples use these two variables. The Python scripts use SF_INSTANCE_URL and SF_ACCESS_TOKEN, so export both names if you want to run everything.
export SF_INSTANCE_URL="$INSTANCE_URL"
export SF_ACCESS_TOKEN="$ACCESS_TOKEN"The access token is a secret. Keep it in an environment variable or a secrets manager. Do not put it in source code, shell history you share, or logs.
The sequence at a glance
Permissions the user needs
A valid token is not enough. The user behind it must be allowed to use the API and to touch the data:
- API Enabled. The user needs this system permission, normally through a profile or permission set. Without it, calls fail with an
API_DISABLED_FOR_ORGorAPI_CURRENT_USER_ACCESS_DISABLEDstyle error. - Object and field permissions. An insert into Contact needs Create on Contact and edit access to every field in your CSV. A bulk query needs Read on the object and its fields.
- OAuth scope. The connected app (or external client app) that issued the token must grant the
apiscope. Thefullscope also works, butapiis the narrower choice.
Bulk API 2.0 runs your records with the permissions of the token's user. It does not elevate them. A load that works for an administrator can fail row by row for an integration user who lacks field access. Those row failures appear in the failed results file, not as an HTTP error.
Endpoint structure
All Bulk API 2.0 paths sit under the REST API version root:
{instance_url}/services/data/v{version}/jobs/{kind}/...Here {kind} is ingest for jobs that write data (insert, update, upsert, delete, hardDelete) and query for jobs that read data. The two families have different sub-resources.
| Method and path | Purpose |
|---|---|
| `POST /jobs/ingest` | Create an ingest job |
| `PUT /jobs/ingest/{id}/batches` | Upload CSV data |
| `PATCH /jobs/ingest/{id}` | Set state to `UploadComplete` or `Aborted` |
| `GET /jobs/ingest/{id}` | Get job state and counts |
| `GET /jobs/ingest/{id}/successfulResults/` | Rows that were saved |
| `GET /jobs/ingest/{id}/failedResults/` | Rows that failed, with errors |
| `GET /jobs/ingest/{id}/unprocessedrecords/` | Rows never attempted |
| `DELETE /jobs/ingest/{id}` | Delete a finished job |
| `GET /jobs/ingest` | List ingest jobs |
| `POST /jobs/query` | Create a query job |
| `GET /jobs/query/{id}` | Get query job state |
| `GET /jobs/query/{id}/results` | Download query results |
The /batches path can mislead you. Bulk API 2.0 has no batches that you create or manage. You upload one body of CSV data to a single job, and Salesforce splits it into internal batches for you. A later chapter covers this.
Choosing the API version
The version number in the path (v62.0 in this tutorial) selects the behavior of the REST API. Pick one version, store it in a single constant, and keep it the same across all calls in a job. Use a version that your org supports. The version list is available at GET {instance_url}/services/data/, which needs no job permissions.
Headers by call type
Header requirements differ depending on the request body:
| Call | Content-Type | Notes |
|---|---|---|
| Create job, change state, create query job | `application/json` | The body is a JSON object |
| Upload data | `text/csv` | The body is raw CSV, sent as bytes |
| Any GET | none needed | Add `Accept: application/json` for job info |
Result downloads return text/csv. Use Accept: application/json only on the job-information GETs. If you send it when downloading results, the call can fail, so leave it off those calls.
A reusable connection helper
Instead of repeating the base URL and header in every call, put them in one place. This Python helper verifies that your token and permissions work by listing ingest jobs. It reads the same environment variables as the later scripts.
import os
import requests
API_VERSION = "v62.0"
class BulkClient:
def __init__(self):
instance = os.environ["SF_INSTANCE_URL"].rstrip("/")
token = os.environ["SF_ACCESS_TOKEN"]
self.base = f"{instance}/services/data/{API_VERSION}/jobs"
self.session = requests.Session()
self.session.headers["Authorization"] = f"Bearer {token}"
def ingest_url(self, job_id=None, suffix=""):
url = f"{self.base}/ingest"
if job_id:
url += f"/{job_id}"
return url + suffix
def check_access(self):
resp = self.session.get(
self.ingest_url(),
headers={"Accept": "application/json"},
)
if resp.status_code == 401:
raise SystemExit("Token expired or invalid: refresh it and retry.")
if resp.status_code == 403:
raise SystemExit(f"Access denied: {resp.text}")
resp.raise_for_status()
return resp.json()
if __name__ == "__main__":
result = BulkClient().check_access()
print("Authenticated. Existing ingest jobs listed:", len(result.get("records", [])))The Session object adds the Authorization header to every request. Later chapters add job creation, upload, and polling as methods on the same class.
Common errors
Authentication and access problems show up as HTTP status codes before any job exists.
| Status | Typical cause | Fix |
|---|---|---|
| 401 `INVALID_SESSION_ID` | Token expired, revoked, or sent to the wrong instance | Refresh the token. Check that `instance_url` is the one returned with it. |
| 403 | The user lacks API access, or IP or session policies block the call | Check API Enabled, connected app policies, and IP restrictions. |
| 404 | Wrong path, a mistyped job ID, or an unsupported API version | Compare the URL with the table above. |
| 400 | Malformed JSON, or an unsupported value such as an invalid `operation` | Read the `message` field in the JSON error body. |
Two further gotchas matter for long loads:
- Tokens expire during long jobs. The job keeps running on Salesforce's side, but your polling calls start failing with 401. Make your loop refresh the token and continue. Do not create a new job.
- Sandbox and production use different hosts. Sandbox tokens come from a different login host and a different instance URL. A token from one org does not work against another org's URL.
Exercise
Your nightly loader ran for four hours. Its polling calls began returning 401 INVALIDSESSIONID after about two hours, but the job's records were still being processed. What should the loader do, and why should it not create a new job?
Show answer
It should obtain a fresh access token (using its OAuth flow, or the refresh mechanism that flow offers) and continue polling the same job ID with the new token. The job lives on Salesforce's side and is not tied to the token that created it. Creating a new job and uploading the data again would process the same records twice, which duplicates inserts or repeats updates.
Exercise
Build the full URL, using instance URL https://example.my.salesforce.com and version v62.0, for fetching failed rows of an ingest job with ID 750xx0000000001AAA.
Show answer
https://example.my.salesforce.com/services/data/v62.0/jobs/ingest/750xx0000000001AAA/failedResults/