Introduction
In our last lesson, we configured a Databricks job to run automatically using a file arrival trigger, an efficient way to build event-driven pipelines through the UI. Now, we will elevate our automation capabilities by moving from UI-driven configuration to programmatic control.
This lesson focuses on the learning outcome: Trigger and monitor Databricks job runs using the REST API.
As a data engineer with experience using tools like Airflow, you understand the power of defining and managing workflows in code. The Databricks REST API provides the same level of control, allowing you to integrate job execution into broader automation frameworks, CI/CD pipelines, or any external application. This skill is crucial for building and managing production systems at scale.
By the end of this lesson, you will be able to:
- Authenticate with the Databricks REST API using a Personal Access Token (PAT).
- Identify and use the key API endpoints for triggering and monitoring jobs.
- Trigger a job run and pass parameters using a REST API client like Postman or a Python script.
- Monitor the status of a job run programmatically by polling its state.
1. Preparing for API Interaction
Before making any API calls, we need two essential pieces of information:
- Your Databricks Workspace URL: This is the base URL for all API endpoints, for example,
https://<your-workspace-instance>.cloud.databricks.com. - A Personal Access Token (PAT): This acts as your password for API authentication. It's a secure string you generate in your user settings.
The following short video explains exactly where to find your workspace URL and how to generate a PAT. It also introduces Postman, a popular tool for testing APIs, which is an excellent way to get started interactively.
Execute a Databricks Job with parameters using the REST API
Watch this first segment from a video by Ike Ellis to learn how to gather the necessary credentials for using the Databricks REST API.
Watch the video from the beginning until 01:22. Focus on how to: Identify the workspace ID (your workspace URL). Navigate to User Settings > Developer > Access tokens to generate a new token. Important: When you generate a token, copy it immediately and store it securely. You will not be able to see it again.
With your workspace URL and PAT, you are ready to start making API calls.
2. Triggering a Job with the REST API
The primary endpoint for running a job on-demand is POST /api/2.1/jobs/run-now. To use it, you need to know the job_id of the job you want to run. You can find this ID in the Databricks UI on the job's detail page.
Let's see how to structure this API call using Postman. This hands-on demonstration will show you how to trigger a job and even override its default parameters.
Execute a Databricks Job with parameters using the REST API
This next segment of the video shows how to use Postman to trigger a job. It covers listing jobs to find an ID, triggering a run with default parameters, and triggering a run while overriding parameters with a JSON payload.
Watch from 03:25 to 07:06. Pay close attention to: Authorization: How the PAT is used as a 'Bearer Token' in the request header. The Request: The structure of the POST request to the jobs/run-now endpoint. The JSON Body: How a JSON payload is used to specify the job_id and override notebook_params. The Response: The API call returns a run_id, which is the unique identifier for this specific execution.
Key Components of the run-now Request
As you saw, a typical request to trigger a job includes:
- Method:
POST - URL:
https://<your-workspace-url>/api/2.1/jobs/run-now - Headers:
Authorization:Bearer <your-personal-access-token>Content-Type:application/json
- Body (JSON):
{ "job_id": 123456789, "notebook_params": { "input_path": "/some/new/data.csv", "process_date": "2024-08-15" } }
The response to a successful run-now call contains the run_id. This ID is essential for the next step: monitoring.

3. Monitoring a Job Run
Once a job is triggered, it goes through several states: PENDING (while waiting for a cluster), RUNNING, and finally a terminal state like TERMINATED (if successful) or FAILED. To build reliable automation, you need to be able to track this progress.
The endpoint for this is GET /api/2.1/jobs/runs/get. It takes the run_id you received from the run-now call as a parameter.
A common pattern is to poll this endpoint in a loop until the job reaches a terminal state. The following video demonstrates exactly this process using a Python script.
Automating Databricks Environment | How to use Databricks Rest API | Databricks Spark Automation
This video from Learning Journal provides an excellent walkthrough of a Python script that not only triggers a job but also monitors its status in a loop.
Watch the following segments: Triggering the Job (18:39 - 20:23): This part shows how to call the jobs/run-now API using Python's requests library and extract the run_id from the response. Monitoring the Status (20:23 - 22:04): This is the key part. Observe how a while loop is used to repeatedly call the jobs/runs/get API. The script parses the JSON response to check the life_cycle_state and waits until it is no longer 'PENDING'.
A Python Snippet for Triggering and Monitoring
Combining these concepts, here is a practical Python script that demonstrates the end-to-end flow. This leverages your experience with Python for a more robust implementation than manual curl or Postman calls.
import requests
import json
import time
import os
# Best practice: use environment variables for secrets and configs
DATABRICKS_HOST = os.getenv("DATABRICKS_HOST") # e.g., "https://<your-workspace-instance>.cloud.databricks.com"
DATABRICKS_TOKEN = os.getenv("DATABRICKS_TOKEN")
JOB_ID = 12345 # Replace with your job's ID
# --- 1. Trigger the Job ---
run_now_url = f"{DATABRICKS_HOST}/api/2.1/jobs/run-now"
headers = {"Authorization": f"Bearer {DATABRICKS_TOKEN}"}
payload = {
"job_id": JOB_ID,
"notebook_params": {
"my_parameter": "value_from_api"
}
}
response = requests.post(run_now_url, headers=headers, json=payload)
if response.status_code == 200:
run_id = response.json()["run_id"]
print(f"Successfully triggered job. Run ID: {run_id}")
else:
print(f"Error triggering job: {response.status_code} - {response.text}")
exit()
# --- 2. Monitor the Job Run ---
get_run_url = f"{DATABRICKS_HOST}/api/2.1/jobs/runs/get"
params = {"run_id": run_id}
while True:
response = requests.get(get_run_url, headers=headers, params=params)
if response.status_code == 200:
run_state = response.json()["state"]
life_cycle_state = run_state.get("life_cycle_state")
result_state = run_state.get("result_state", "N/A")
print(f"Run ID {run_id} is in state: {life_cycle_state}")
if life_cycle_state in ["TERMINATED", "SKIPPED", "INTERNAL_ERROR"]:
print(f"Job run finished with result state: {result_state}")
if result_state != "SUCCESS":
# Handle failure
pass
break
time.sleep(30) # Wait for 30 seconds before polling again
else:
print(f"Error getting run status: {response.status_code} - {response.text}")
break
This script encapsulates the entire process: triggering the job, extracting the run_id, and then polling the runs/get endpoint until the job completes.
Conclusion
In this lesson, you've bridged the gap between UI-based automation and full programmatic control of your Databricks workflows. By mastering the REST API, you unlock the ability to integrate Databricks into any external system, from a custom Python script to a sophisticated CI/CD platform.
Key Takeaways:
- Authentication is Key: All API requests must be authenticated using a Personal Access Token (PAT) in the
Authorizationheader. - Trigger with
run-now: ThePOST /api/2.1/jobs/run-nowendpoint is used to start a job. You must provide ajob_id, and you can optionally pass parameters in the JSON body. This call returns arun_id. - Monitor with
runs/get: TheGET /api/2.1/jobs/runs/getendpoint, using therun_id, allows you to poll the status of a specific job run. - The State Model: A job run progresses through a
life_cycle_state(e.g.,PENDING,RUNNING,TERMINATED). Upon completion, it has aresult_state(e.g.,SUCCESS,FAILED). - Programmatic Control is Power: Using tools like Postman for exploration and Python scripts for implementation gives you the power to automate, test, and integrate Databricks jobs at a professional level.
Preview of the Next Lesson:
We have now seen how to trigger and monitor jobs that already exist. But what about managing the job definitions themselves? In the next lesson, "Update job configurations and promote changes between environments using the REST API," we will explore how to use the API to create, update, and delete job specifications, enabling true end-to-end automation for your deployment pipelines.