Skip to main content

Lakeflow Integrations reference

Beta

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.

Python
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

display_name

str

Required. The name shown in the Add task dialog.

description

str

Optional. A description of the integration.

icon

str

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.

parameters

Mapping[str, ParameterMetadata]

Optional. Customizes how parameters appear in the task form, keyed by parameter name. See ParameterMetadata.

promoted_parameter

str

Optional. The name of a parameter whose value is shown on the task's node in the job graph. Must be a str, int, float, bool, Enum, or connection parameter.

Argument

Type

Description

display_name

str

Required. The name shown in the Add task dialog.

description

str

Optional. A description of the integration.

icon

str

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.

parameters

Mapping[str, ParameterMetadata]

Optional. Customizes how parameters appear in the task form, keyed by parameter name. See ParameterMetadata.

promoted_parameter

str

Optional. The name of a parameter whose value is shown on the task's node in the job graph. Must be a str, int, float, bool, Enum, or connection parameter.

Example​

Python
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

str, int, float

Text or number field

Single-line values.

bool

Toggle

Flags.

Enum subclass

Select over the enum's member names

A fixed set of choices that aren't true or false.

TextAreaParameter

Multi-line text box

Multi-line text, such as message bodies or queries.

list[T], set[T], or dict[str, T], where T is str, int, float, bool, or an Enum subclass

List or key-value input

Collections of simple values, such as labels or HTTP headers.

TextAreaParameter, parsed with json.loads

Multi-line text box

Nested JSON structures only, such as Slack Block Kit blocks.

Annotated[HttpUcConnectionParameter, HttpConnectionFilter(...)]

Unity Catalog HTTP connection picker, filtered to a host and base path

Sending requests to external services. See HttpUcConnectionParameter.

Annotation

Form field

Use for

str, int, float

Text or number field

Single-line values.

bool

Toggle

Flags.

Enum subclass

Select over the enum's member names

A fixed set of choices that aren't true or false.

TextAreaParameter

Multi-line text box

Multi-line text, such as message bodies or queries.

list[T], set[T], or dict[str, T], where T is str, int, float, bool, or an Enum subclass

List or key-value input

Collections of simple values, such as labels or HTTP headers.

TextAreaParameter, parsed with json.loads

Multi-line text box

Nested JSON structures only, such as Slack Block Kit blocks.

Annotated[HttpUcConnectionParameter, HttpConnectionFilter(...)]

Unity Catalog HTTP connection picker, filtered to a host and base path

Sending requests to external services. See HttpUcConnectionParameter.

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:

Python
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.

Python
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 SlackConnection above, with an HttpConnectionFilter that's as narrow as the API allows.
  • Pass a path relative 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 path as a single segment, with urllib.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

display_name

str

The label shown for the parameter. Defaults to the parameter name.

description

str

The tooltip text shown next to the label.

placeholder

str

The hint text shown in the empty input.

Field

Type

Description

display_name

str

The label shown for the parameter. Defaults to the parameter name.

description

str

The tooltip text shown next to the label.

placeholder

str

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.

Sensor

Defers until poll returns PollResult.completed().

Waiting on an external condition, such as a file arriving.

Operator

Starts work, polls until it's done, and cleans up after itself.

Long-running external work that doesn't need constant compute to orchestrate.

Type

What it does

Use for

Function

Runs one time.

Small workloads that finish within a few seconds, such as posting a message.

Sensor

Defers until poll returns PollResult.completed().

Waiting on an external condition, such as a file arriving.

Operator

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​

Python
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 what poll needs, such as an external ID, with ctx.set_task_value.
  • poll(self, ctx: Context) -> PollResult: Required. Called repeatedly after open. Returns PollResult.completed() when the work finishes, or PollResult.deferred(duration) to release compute and poll again later.
  • close(self, ctx: Context) -> None: Optional. Cancels or cleans up the external work. Runs when poll completes, when the task fails, or when the run is canceled. It can run more than one time, so it must be idempotent.

Example​

Python
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"))
important

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

main

str

The integration's main entry point, which is the function, Sensor class, or Operator class that the task runs.

task_key

str

The key of the task running the integration.

job_run_id

int

The ID of the current job run.

task_run_id

int

The ID of the current task run.

job_id

int

The ID of the job the task belongs to.

for_each_index

int or None

The index of the current For each iteration, or None outside a For each task.

Attribute

Type

Description

main

str

The integration's main entry point, which is the function, Sensor class, or Operator class that the task runs.

task_key

str

The key of the task running the integration.

job_run_id

int

The ID of the current job run.

task_run_id

int

The ID of the current task run.

job_id

int

The ID of the job the task belongs to.

for_each_index

int or None

The index of the current For each iteration, or None outside a For each task.

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 no default is provided.

PollResult​

Returned by Sensor.poll and Operator.poll to indicate whether the task has completed or should be deferred.

Field

Type

Description

status

"completed" or "deferred"

The outcome of the poll.

defer_for

datetime.timedelta

How long to defer before the next poll. Only set when deferred.

Field

Type

Description

status

"completed" or "deferred"

The outcome of the poll.

defer_for

datetime.timedelta

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 after duration, 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

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

  • app
  • arrow-in
  • at
  • backup
  • bar-chart
  • beaker
  • binary
  • book
  • bookmark
  • brackets-curly
  • brackets-square
  • branch
  • briefcase
  • brush
  • bug
  • calendar
  • camera
  • catalog
  • chain
  • chart-line
  • check-circle
  • checklist
  • chip
  • clipboard
  • clock
  • cloud
  • cloud-database
  • code
  • columns
  • compass
  • connect
  • copy
  • dag
  • dashboard
  • database
  • decimal
  • dollar
  • download
  • erd
  • face-smile
  • file
  • filter
  • flag
  • flow
  • folder
  • fork
  • function
  • gear
  • gift
  • globe
  • grid
  • hash
  • history
  • home
  • image
  • ingestion
  • key
  • layer
  • leaf
  • letters
  • lightbulb
  • lightning
  • link
  • list
  • lock
  • mail
  • map
  • measure
  • megaphone
  • models
  • moon
  • notebook
  • notification
  • numbers
  • office
  • pencil
  • pie-chart
  • pipeline
  • play
  • plug
  • puzzle
  • query
  • refresh
  • robot
  • rocket
  • rows
  • school
  • search
  • send
  • share
  • shield
  • sliders
  • sparkle
  • speech-bubble
  • speedometer
  • star
  • storefront
  • stream
  • sun
  • sync
  • table
  • tag
  • target
  • terminal
  • trash
  • tree
  • trending
  • upload
  • user
  • user-group
  • visible
  • workflows
  • wrench
  • zoom-in