Sub topic 11
Using the Databricks SDK for Python
The Databricks SDK for Python wraps the REST API in typed Python objects. It handles authentication, pagination, retries and error classes, so your script describes what to do instead of how to call HTTP.
This chapter assumes you have read the earlier chapters on authentication, profiles and the Jobs API. You should also be comfortable with Python functions, exceptions and iterators.
Where the SDK fits
Earlier chapters showed three ways to reach the same endpoints: the CLI, curl, and requests. The SDK sits on top of the same REST API. A call such as w.jobs.list() becomes GET /api/2.1/jobs/list, with pages fetched for you.
| Need | Best fit |
|---|---|
| One-off command or shell pipeline | CLI with `jq` |
| Deploy resources from version control | Asset Bundles |
| Logic, loops, error handling, tests | SDK |
| Endpoint the SDK does not cover yet | `w.api_client.do()` or `databricks api` |
Install it into a virtual environment:
python -m venv .venv
source .venv/bin/activate
pip install databricks-sdkThe client and unified authentication
WorkspaceClient is the entry point for workspace-level APIs. Account-level APIs use a separate AccountClient, covered in a later chapter.
When you create a client with no arguments, the SDK looks for credentials in a fixed order. This is called unified authentication, and the CLI uses the same rules.
The same code therefore works on a laptop with a profile, in CI with environment variables, and in a job with a service principal.
from databricks.sdk import WorkspaceClient
# 1. Defaults: environment variables, then the DEFAULT profile
w = WorkspaceClient()
# 2. A named profile from ~/.databrickscfg
w_dev = WorkspaceClient(profile="dev")
# Confirm which identity the client is acting as
print(w_dev.current_user.me().user_name)You can also pass host= and token= directly. Avoid that in committed code, because it invites hard-coded secrets. For unattended automation, prefer OAuth machine-to-machine credentials for a service principal. Set DATABRICKS_HOST, DATABRICKS_CLIENT_ID and DATABRICKS_CLIENT_SECRET, and the SDK exchanges them for short-lived tokens and refreshes them as needed.
Working model: services, methods, dataclasses
The client exposes one attribute per API area, such as w.jobs, w.clusters, w.secrets and w.workspace. Each has methods that map to endpoints. Requests take keyword arguments. Responses come back as dataclasses, so you read job.settings.name instead of job["settings"]["name"].
from databricks.sdk import WorkspaceClient
w = WorkspaceClient()
for job in w.jobs.list():
print(job.job_id, job.settings.name)This is the SDK equivalent of the curl and CLI listings from earlier chapters. Two properties matter:
- List methods return iterators.
w.jobs.list()requests the next page only when the loop needs it. You never handlenext_page_tokenorhas_moreyourself. - Fields can be
None. The API omits fields that are unset, and the dataclass keeps them asNone. Guard optional nested fields, for examplejob.settings.name if job.settings else None.
Wrap a list in list(...) only when you need the whole result in memory. For large workspaces, filter on the server with a parameter such as name="demo_job" so you fetch fewer pages.
Triggering a job and waiting for it
In the REST chapter you wrote a polling loop with time.sleep(15). The SDK folds that into a waiter. Methods for long-running operations return a Wait object. Calling .result() blocks until the operation reaches a terminal state.
from datetime import timedelta
from databricks.sdk import WorkspaceClient
w = WorkspaceClient()
waiter = w.jobs.run_now(job_id=123)
print("started run", waiter.response.run_id)
run = waiter.result(timeout=timedelta(minutes=30))
state = run.state
print(state.life_cycle_state, state.result_state, state.state_message)
if state.result_state is None or state.result_state.value != "SUCCESS":
raise SystemExit(f"run {waiter.response.run_id} did not succeed")Three details are easy to get wrong:
.result()returns when the run is terminal, not when it succeeds. A run whose tasks failed ends inTERMINATEDwithresult_stateset toFAILED, and no exception is raised. Always checkresult_state..result()raisesTimeoutErrorif the deadline passes. The run keeps going on Databricks. Cancel it withw.jobs.cancel_run(run_id=...)if you do not want that.- If you only want to start the run, call
run_nowand ignore the waiter. The run starts when the request is sent, not when you call.result().
To pass parameters, use the argument that matches how the job was defined. For a job with job parameters, that is job_parameters={"date": "2026-12-04"}.
Handling errors
HTTP errors from the API become Python exceptions, all subclasses of DatabricksError. The SDK maps status codes and error codes to specific classes, so you can catch what you expect.
from databricks.sdk import WorkspaceClient
from databricks.sdk.errors import DatabricksError, NotFound, PermissionDenied
w = WorkspaceClient()
def describe_job(job_id: int) -> str:
try:
job = w.jobs.get(job_id=job_id)
except NotFound:
return f"job {job_id} does not exist"
except PermissionDenied:
return f"no permission to view job {job_id}"
except DatabricksError as err:
return f"API error: {err}"
return job.settings.name
print(describe_job(123))Order the except clauses from specific to general. The base class goes last.
The SDK retries some transient failures on its own, including HTTP 429 (rate limited) and 503 responses, with backoff. This covers most rate-limit trouble, but it does not make a script that hammers an endpoint safe. If you loop over thousands of items, add your own batching or delay.
Escape hatch: raw calls
The SDK lags behind new endpoints and does not cover preview features. When a method is missing, send a raw request through the same authenticated client:
from databricks.sdk import WorkspaceClient
w = WorkspaceClient()
result = w.api_client.do("GET", "/api/2.1/jobs/list", query={"limit": 5})
print(result.get("jobs", []))You keep authentication, retries and error mapping, and you lose typed responses. The result is a plain dictionary.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `ValueError: default auth: cannot configure default credentials` | No env vars and no usable profile | Set `DATABRICKS_HOST` and a credential, or pass `profile=` |
| `PermissionDenied` on calls that work in the UI | The token or service principal lacks access to that object | Grant the identity the right permission on the job or cluster |
| Script reports success but the job failed | Only checked that `.result()` returned | Inspect `run.state.result_state` |
| `AttributeError: 'NoneType' object has no attribute 'name'` | Optional field was unset | Guard nested fields before reading them |
| `TimeoutError` from `.result()` | Run took longer than the timeout | Raise the timeout, or poll separately and cancel if needed |
Exercise
A CI script calls w.jobs.run_now(job_id=123).result() and exits with status 0 whenever no exception is raised. The nightly job fails, but CI stays green. Why, and what is the fix?
Show answer
.result() waits for the run to reach a terminal life-cycle state, and a run whose tasks failed is terminal (TERMINATED with result_state FAILED), so no exception is raised. Read the returned run's state.result_state and exit non-zero unless it equals SUCCESS. Also pass a timeout so the script cannot wait forever.
Exercise
You need to list all jobs named demo_job. Why is w.jobs.list(name="demo_job") usually better than filtering after w.jobs.list()?
Show answer
The filter runs on the server, so fewer pages are fetched and fewer objects are transferred. The iterator still pages lazily either way, but client-side filtering has to request every page of every job first.