Sub topic 8
Triggering and monitoring a job run
This chapter covers how to start an existing Databricks job through the Jobs REST API and wait for it to finish. It assumes you can set DATABRICKS_HOST and DATABRICKS_TOKEN environment variables, read JSON, and write basic Python. It builds on the REST API basics chapter.
The two calls you need
A job run takes two endpoints:
POST /api/2.1/jobs/run-nowstarts a run of an existing job and returns arun_id.GET /api/2.1/jobs/runs/get?run_id=...returns the current state of that run.
The job itself must already exist. You need its job_id, which you can find with databricks jobs list.
Starting a run with curl
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 response is a small JSON object such as {"run_id": 456789, "number_in_job": 1}. Keep the run_id. It identifies this one run, not the job.
Understanding run state
The state object in the run response has two fields that people often confuse.
life_cycle_statesays where the run is in its life. Common values arePENDING,RUNNING,TERMINATING,TERMINATED,SKIPPED, andINTERNAL_ERROR.result_statesays how the run ended. It appears only after the run finishes. Common values areSUCCESS,FAILED,TIMEDOUT, andCANCELED.
A run that reaches TERMINATED has finished, but it may have finished with FAILED. Always check result_state before you treat the run as a success.
Polling in Python
This script starts a run, then checks it every 15 seconds until the life-cycle state is terminal.
import os
import time
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()
run_id = resp.json()["run_id"]
while True:
r = requests.get(f"{host}/api/2.1/jobs/runs/get", headers=headers, params={"run_id": run_id})
r.raise_for_status()
state = r.json()["state"]
if state["life_cycle_state"] in ("TERMINATED", "SKIPPED", "INTERNAL_ERROR"):
print(state.get("result_state"), state.get("state_message"))
break
time.sleep(15)Three details matter here:
raise_for_status()turns HTTP errors such as 401 or 404 into exceptions, so the loop does not spin on a bad response.state.get("result_state")is used because the field is missing forSKIPPEDandINTERNAL_ERRORruns.- The 15-second sleep keeps the request rate low. Polling every second gains little and risks rate limiting.
Common errors
- Using
job_idwhererun_idis needed.runs/gettakes the run ID returned byrun-now. - Treating
TERMINATEDas success. Check thatresult_stateequalsSUCCESS. - No exit code. A script that only prints the result gives CI no way to see a failure. Call
sys.exit(1)when the result is notSUCCESS. - No timeout. A hung run makes the loop run forever. Add a deadline, for example by stopping after a set number of minutes.
Exercise
A polling script prints "TERMINATED" and your pipeline reports success, but the job's notebook raised an error. Which field should the script have checked, and what value means success?
Show answer
It should have checked result_state. TERMINATED is a life_cycle_state value that only says the run is over. A successful run has result_state equal to SUCCESS. A failed notebook gives FAILED.
Exercise
Why does the sample script use state.get("result_state") instead of state["result_state"]?
Show answer
The result_state field is not present in every terminal run. A run that ends as SKIPPED or INTERNAL_ERROR has no result state, so indexing directly would raise a KeyError. get returns None instead.