Sub topic 7
REST API basics
This chapter covers how the Databricks REST API is organized and how to call it with curl and Python. It assumes you can use a shell and environment variables, understand HTTP methods and JSON, and know what a Databricks job and cluster are. It also assumes you have a workspace URL and a credential from the authentication chapter. Running jobs and handling pagination come in later chapters.
What the REST API is
Everything the web UI and the CLI do goes through the Databricks REST API. The CLI is a wrapper around it. Calling the API directly is useful when you work in a language or environment without the CLI, when you need an endpoint the CLI does not wrap, or when you want full control over requests.
An API call has four parts:
- A host, such as
https://<workspace-host>. - A path, such as
/api/2.1/jobs/list. - An HTTP method, usually
GETorPOST. - An
Authorizationheader that carries a credential.
Databricks sends and receives JSON. For POST requests you send a JSON body and set Content-Type: application/json. For GET requests you send parameters in the query string.
Host and path structure
The host is your workspace URL. It has no trailing path, and it is the same value you use in databricks auth login --host. Many scripts store it in DATABRICKS_HOST. Strip any trailing slash before you append a path, or you will produce a double slash.
Paths follow the pattern /api/<version>/<service>/<operation>. Examples:
| Path | Method | Purpose |
|---|---|---|
| `/api/2.1/jobs/list` | GET | List jobs |
| `/api/2.1/jobs/run-now` | POST | Start a run of an existing job |
| `/api/2.1/jobs/runs/get` | GET | Get the state of one run |
| `/api/2.0/clusters/list` | GET | List clusters |
| `/api/2.0/preview/scim/v2/Me` | GET | Show the calling identity |
Note that the version number is part of the path and differs between services. The Jobs API is at 2.1, while many older services remain at 2.0. Always check the API reference for the version of the endpoint you need. Using the wrong version can return a 404 or a response with different fields.
Bearer authentication
Each request must carry a credential in the Authorization header using the Bearer scheme:
Authorization: Bearer <token>The token can be a personal access token (PAT) or an OAuth access token. Both go in the same header. The difference is lifetime. A PAT lives until it expires or you revoke it. An OAuth access token is short-lived, usually about an hour, so long-running scripts must refresh it.
You can get an OAuth token from the CLI without handling the OAuth flow yourself:
databricks auth token --host https://<workspace-host>The command prints JSON that includes an access_token field. This is useful for one-off curl calls after you have logged in with databricks auth login.
Never type a token into a command line or a script. Read it from an environment variable, as the examples below do. The credential chapter covers this further.
A first request with curl
This request starts a run of an existing job. It is the same call used in later chapters on jobs.
curl -sS -X POST "$DATABRICKS_HOST/api/2.1/jobs/run-now" \
-H "Authorization: Bearer $DATABRICKS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"job_id": 123}'The flags matter:
-shides the progress meter, and-Sstill shows errors. Used together they keep output clean without hiding failures.-X POSTsets the method.- Each
-Hadds a header. -dsends the request body. Single quotes keep the shell from touching the JSON.
A successful response is JSON such as {"run_id": 456, "number_in_job": 1}. Keep the run_id, because you use it to check the run.
By default curl exits with code 0 even when the server returns an error status such as 401 or 404. Add --fail-with-body (curl 7.76 and later) so the exit code reflects HTTP errors and you still see the error body. This matters in shell scripts that use set -e.
The same request in Python
With the requests library, the same call looks like this:
import os
import requests
host = os.environ["DATABRICKS_HOST"].rstrip("/")
headers = {"Authorization": f"Bearer {os.environ['DATABRICKS_TOKEN']}"}
resp = requests.post(
f"{host}/api/2.1/jobs/run-now",
headers=headers,
json={"job_id": 123},
)
resp.raise_for_status()
print(resp.json()["run_id"])Three details are worth noting:
json=serializes the body and sets theContent-Typeheader for you.raise_for_status()raises an exception for any4xxor5xxresponse. Without it, a failed call returns silently andresp.json()may not contain the field you expect.- A
requests.Sessionwith the header set once avoids repeatingheaders=and reuses the connection when you make many calls.
For GET requests, pass query parameters with params=:
r = requests.get(
f"{host}/api/2.1/jobs/runs/get",
headers=headers,
params={"run_id": 456},
timeout=30,
)
r.raise_for_status()
print(r.json()["state"])Set timeout on every call. requests has no default timeout, so a stalled connection can hang your script forever.
What happens in one request
The sequence below shows a call and the two common failure paths.
Reading responses and errors
Databricks returns errors as JSON with an error_code and a message. For example:
{
"error_code": "RESOURCE_DOES_NOT_EXIST",
"message": "Job 999 does not exist."
}Use the HTTP status as the first signal and the error_code as the second. These are the ones you will meet most often:
| Status | Typical meaning | What to check |
|---|---|---|
| 400 | Malformed request or invalid field | JSON syntax, field names, value types |
| 401 | Credential missing, expired, or revoked | Token value, OAuth expiry, correct host |
| 403 | Authenticated but not permitted | Job or cluster permissions, workspace entitlements |
| 404 | Path or resource not found | API version, path spelling, job ID |
| 429 | Rate limit exceeded | Back off and retry |
| 5xx | Server-side problem | Retry with a delay |
The most common mistake is a 401 caused by a token that belongs to a different workspace than the host you are calling. A token is valid only for the workspace, or account, that issued it. Another common mistake is a 400 caused by sending "job_id": "123" as a string when the API expects a number.
A 200 response does not always mean success of the underlying work. Starting a run returns 200 as soon as the run is accepted. Whether the job succeeds is reported later in the run state, which the next chapter covers.
Checking your setup before scripting
Before you write a larger script, test the credential against a cheap read-only endpoint. The SCIM Me endpoint returns the identity behind the token:
curl -sS --fail-with-body \
-H "Authorization: Bearer $DATABRICKS_TOKEN" \
"$DATABRICKS_HOST/api/2.0/preview/scim/v2/Me"If this returns your user name, the host and token are paired correctly. If it fails, fix that first. Otherwise you may spend time debugging a job call when the cause is the credential.
Choosing between curl, Python, the CLI, and the SDK
| Tool | Best for | Trade-off |
|---|---|---|
| `curl` | Quick checks, simple shell steps | No built-in retry or pagination |
| Python with `requests` | Custom logic, polling loops | You write error handling yourself |
| CLI | Interactive work and shell scripts | Needs installation |
| SDK | Larger Python programs | Adds a dependency |
Raw HTTP gives the most control and the fewest dependencies. It also leaves authentication refresh, retries, and pagination to you. The later chapters on pagination and the SDK show how to reduce that work.
Exercise
A script calls POST $DATABRICKS_HOST/api/2.1/jobs/run-now with a valid personal access token for workspace A, but DATABRICKS_HOST points at workspace B. What HTTP status do you expect, and how would you confirm the cause with one extra request?
Show answer
Expect 401, because a token is valid only for the workspace that issued it. Confirm it by calling GET $DATABRICKS_HOST/api/2.0/preview/scim/v2/Me with the same token. That call fails with the same 401 against workspace B, and it succeeds when the host is changed to workspace A.
Exercise
In a Python script using requests, a call to jobs/run-now fails with a 400, but the script then crashes on resp.json()["run_id"] with a KeyError. Which two lines would you add or change so the real error is visible?
Show answer
Call resp.raise_for_status() right after the request so the 4xx response raises an exception. Also set a timeout on the call. To see the server's explanation, catch the exception and print resp.text, which holds the JSON error_code and message.