Lakeflow Integrations reference
This feature is in Beta.
This page describes the Python API for authoring Lakeflow Integrations and the YAML schema that registers them.
databricks.lakeflow.integrations package
Import these objects from the databricks.lakeflow.integrations package to define functions, sensors, and operators.
from databricks.lakeflow.integrations import (
Context,
HttpConnectionFilter,
HttpUcConnectionParameter,
Operator,
ParameterMetadata,
PollResult,
Sensor,
TextAreaParameter,
integration,
)
@integration
The @integration decorator marks a function, a Sensor class, or an Operator subclass as an integration. When you deploy the bundle, it generates the integration YAML that registers the integration. Entry points must be synchronous, so @integration rejects async functions and methods.
Argument | Type | Description |
|---|---|---|
|
| Required. The name shown in the Add task dialog. |
|
| Optional. A description of the integration. |
|
| Optional. A Databricks icon shown in the task palette and on the job graph. See available icon values. Unknown names fall back to a generic icon. |
|
| Optional. Customizes how parameters appear in the task form, keyed by parameter name. See |
|
| Optional. The name of a parameter whose value is shown on the task's node in the job graph. Must be a |
Example
from databricks.lakeflow.integrations import ParameterMetadata, integration
@integration(
display_name="Post to external service",
icon="send",
promoted_parameter="target",
parameters=dict(
target=ParameterMetadata(
display_name="Target",
description="Where to post the message.",
placeholder="For example, alerts",
),
),
)
def post(target: str, message: str) -> None: ...
Parameters
The parameters of a function, or of a sensor's or operator's __init__ method, become task parameters and the fields of the task form. Parameter types map to custom UI components in the task editor, so users can enter values easily. Use the most specific annotation that fits:
Annotation | Form field | Use for |
|---|---|---|
| Text or number field | Single-line values. |
| Toggle | Flags. |
| Select over the enum's member names | A fixed set of choices that aren't true or false. |
| Multi-line text box | Multi-line text, such as message bodies or queries. |
| List or key-value input | Collections of simple values, such as labels or HTTP headers. |
| Multi-line text box | Nested JSON structures only, such as Slack Block Kit blocks. |
| Unity Catalog HTTP connection picker, filtered to a host and base path | Sending requests to external services. See |
A parameter without a default value is required. Default every Optional[...] parameter to None so that it's optional in the form.
For nested JSON, accept a TextAreaParameter and parse it yourself, so that you can raise a clear error when the JSON is invalid:
import json
from typing import Optional
from databricks.lakeflow.integrations import TextAreaParameter, integration
@integration(display_name="Send Slack message")
def send_slack_message(channel: str, message: TextAreaParameter, blocks: Optional[TextAreaParameter] = None) -> None:
try:
parsed_blocks = json.loads(blocks) if blocks else None
except json.JSONDecodeError as error:
raise ValueError(f"Blocks must be valid JSON: {error}") from error
...
Don't use bare list or dict annotations, which render as a text field that takes JSON. Use typed collections for simple values, or a TextAreaParameter for nested JSON.
HttpUcConnectionParameter
A str subclass that holds the name of a Unity Catalog HTTP connection. To offer only connections to a specific service, annotate the parameter with HttpConnectionFilter, which takes optional host and base_path arguments that must match exactly.
Call the service with WorkspaceClient().serving_endpoints.http_request(conn=connection, ...), which authenticates with the connection's credentials.
from typing import Annotated
from databricks.lakeflow.integrations import HttpConnectionFilter, HttpUcConnectionParameter, integration
from databricks.sdk import WorkspaceClient
from databricks.sdk.service.serving import ExternalFunctionRequestHttpMethod
SlackConnection = Annotated[HttpUcConnectionParameter, HttpConnectionFilter(host="https://slack.com", base_path="/api")]
@integration(display_name="Send Slack message")
def send_slack_message(connection: SlackConnection, channel: str, message: str) -> None:
WorkspaceClient().serving_endpoints.http_request(
conn=connection,
method=ExternalFunctionRequestHttpMethod.POST,
path="chat.postMessage",
json={"channel": channel, "text": message},
)
Follow these practices when you call external services:
- Reach every external service through a Unity Catalog connection parameter. Keep credentials, tokens, and hosts only in the connection, never in code, parameters, or files.
- Define the connection type at module level, such as
SlackConnectionabove, with anHttpConnectionFilterthat's as narrow as the API allows. - Pass a
pathrelative to the connection's base path. Never build an absolute URL or host from parameter values. - URL-encode each user-provided value that you add to
pathas a single segment, withurllib.parse.quote(value, safe=""). Reject.and... - Raise an error with the service's message for non-JSON responses and for API errors that return a success status code.
TextAreaParameter
A str subclass that renders a multi-line text box in the task form. Use it for multi-line text, and for nested JSON that you parse with json.loads.
ParameterMetadata
Customizes how a parameter appears in the task form.
Field | Type | Description |
|---|---|---|
|
| The label shown for the parameter. Defaults to the parameter name. |
|
| The tooltip text shown next to the label. |
|
| The hint text shown in the empty input. |
Write parameter descriptions as short, complete sentences, often just an example, such as For example, DATA-123. Name parameters after what the user knows rather than what the API takes, such as an assignee_email that the integration resolves to an account ID.
Functions, sensors, and operators
Type | What it does | Use for |
|---|---|---|
Function | Runs one time. | Small workloads that finish within a few seconds, such as posting a message. |
Defers until | Waiting on an external condition, such as a file arriving. | |
Starts work, polls until it's done, and cleans up after itself. | Long-running external work that doesn't need constant compute to orchestrate. |
Functions
A function runs one time. Its return value is ignored. To fail the task, raise an exception with a message that the user can act on. To pass a value to downstream tasks, set a task value with WorkspaceClient().dbutils.jobs.taskValues.set(key=..., value=...).
Sensor
A protocol for classes that poll an external condition and either complete or defer.
Sensor has one method, poll(self, ctx: Context) -> PollResult, which is called on each attempt. Return PollResult.completed() when the condition is met, or PollResult.deferred(duration) to release compute and try again later.
Example
import datetime
from databricks.lakeflow.integrations import Context, PollResult, Sensor, integration
from databricks.sdk import WorkspaceClient
@integration(display_name="Wait for run")
class WaitForRunSensor(Sensor):
def __init__(self, run_id: int):
self.run_id = run_id
def poll(self, ctx: Context) -> PollResult:
run = WorkspaceClient().jobs.get_run(run_id=self.run_id)
if run.state and run.state.result_state:
return PollResult.completed()
return PollResult.deferred(datetime.timedelta(minutes=1))
Operator
An abstract base class for long-running external work with an open, poll, and close lifecycle.
Operator has the following methods:
open(self, ctx: Context) -> None: Optional. Called at most one time, before the first poll. Starts the external work and saves whatpollneeds, such as an external ID, withctx.set_task_value.poll(self, ctx: Context) -> PollResult: Required. Called repeatedly afteropen. ReturnsPollResult.completed()when the work finishes, orPollResult.deferred(duration)to release compute and poll again later.close(self, ctx: Context) -> None: Optional. Cancels or cleans up the external work. Runs whenpollcompletes, when the task fails, or when the run is canceled. It can run more than one time, so it must be idempotent.
Example
import datetime
from databricks.lakeflow.integrations import Context, Operator, PollResult, integration
from databricks.sdk import WorkspaceClient
@integration(display_name="Run job and wait")
class RunJobOperator(Operator):
def __init__(self, job_id: int):
self.job_id = job_id
def open(self, ctx: Context) -> None:
run = WorkspaceClient().jobs.run_now(job_id=self.job_id)
ctx.set_task_value("run_id", run.run_id)
def poll(self, ctx: Context) -> PollResult:
run = WorkspaceClient().jobs.get_run(run_id=ctx.get_task_value("run_id"))
if run.state and run.state.result_state:
return PollResult.completed()
return PollResult.deferred(datetime.timedelta(minutes=5))
def close(self, ctx: Context) -> None:
WorkspaceClient().jobs.cancel_run(run_id=ctx.get_task_value("run_id"))
Sensors and operators are re-created before every call, so instance attributes other than parameters don't survive a deferral. Save state with ctx.set_task_value and read it back with ctx.get_task_value.
Context
Passed to Sensor and Operator methods, and provides information on the task run.
Context has the following attributes:
Attribute | Type | Description |
|---|---|---|
|
| The integration's main entry point, which is the function, |
|
| The key of the task running the integration. |
|
| The ID of the current job run. |
|
| The ID of the current task run. |
|
| The ID of the job the task belongs to. |
|
| The index of the current For each iteration, or |
Context has the following methods:
set_task_value(key, value): Saves state that must survive a deferral, such as an external ID. The value is stored as a task value, so downstream tasks can also read it. In a For each task, each iteration keeps its own value.get_task_value(key, default=None): Reads a value set earlier in this task run. Raises an error if the key isn't set and nodefaultis provided.
PollResult
Returned by Sensor.poll and Operator.poll to indicate whether the task has completed or should be deferred.
Field | Type | Description |
|---|---|---|
|
| The outcome of the poll. |
|
| How long to defer before the next poll. Only set when deferred. |
PollResult has the following methods:
PollResult.completed(): The condition was met or the work finished, and the task finishes successfully.PollResult.deferred(duration): The task is rescheduled afterduration, and compute is released in the meantime.
SensorResult is an alias of PollResult that remains available for integrations written for earlier versions of the preview.
Lakeflow Integration YAML
The bundle template generates the Lakeflow Integration YAML automatically for any function or class annotated with @integration. Don't edit a generated definition. Instead, change the Python source and deploy again. The UI discovers available integrations by inspecting /Workspace/.lakeflow_integrations.yml and /Workspace/Users/<user>/.lakeflow_integrations.yml.
Example integration YAML
schema: lakeflow-integration-v0.1.0
name: Post to external service
description: Posts a message to an external service
icon:
name: send # A known Databricks icon. See the list of available icon options.
library: databricks # The only available option.
main: my_lakeflow_integrations.post.post
promoted_parameter: target # The parameter whose value is shown on the task's node in the job graph.
environment:
environment_version: '5'
dependencies: # Must include the Python wheel that contains the integration.
- /Workspace/Shared/integrations/my_lakeflow_integrations-0.1.0-py3-none-any.whl
config:
type: object
properties:
connection: # The name of your parameter.
type: string
title: Connection # The title to render in the UI instead of the raw parameter name.
description: Unity Catalog connection to the service.
x-ui:
widget: select_uc_connection # Renders a Unity Catalog connection picker.
connection_type: HTTP
host: https://api.example.com # Optional. Only offer connections to this host.
base_path: /v1 # Optional. Only offer connections with this base path.
target:
type: string
title: Target
description: Where to post the message.
default: alerts # Default value for new task instances.
placeholder: For example, alerts # Hint text shown in the empty input.
message:
type: string
title: Message
description: Message body.
x-ui:
widget: textarea # The widget to render, such as textarea or select_uc_connection.
required: # Parameters listed here are marked as required in the UI.
- connection
- target
- message
For the full list of icon values, expand Available icon values.
Available icon values
apparrow-inatbackupbar-chartbeakerbinarybookbookmarkbrackets-curlybrackets-squarebranchbriefcasebrushbugcalendarcameracatalogchainchart-linecheck-circlechecklistchipclipboardclockcloudcloud-databasecodecolumnscompassconnectcopydagdashboarddatabasedecimaldollardownloaderdface-smilefilefilterflagflowfolderforkfunctiongeargiftglobegridhashhistoryhomeimageingestionkeylayerleafletterslightbulblightninglinklistlockmailmapmeasuremegaphonemodelsmoonnotebooknotificationnumbersofficepencilpie-chartpipelineplayplugpuzzlequeryrefreshrobotrocketrowsschoolsearchsendshareshieldsliderssparklespeech-bubblespeedometerstarstorefrontstreamsunsynctabletagtargetterminaltrashtreetrendinguploaduseruser-groupvisibleworkflowswrenchzoom-in