Chapter 5. Using the AI pipelines REST API with Kubeflow pipelines SDK
You can use the Kubeflow pipelines SDK and AI Pipelines REST API to programmatically manage AI pipelines, pipeline versions, experiments, runs, and other resources. This enables automation and integration with external applications.
5.1. Overview of AI Pipelines REST API and SDK Copy linkLink copied to clipboard!
The AI Pipelines service provides a RESTful API that allows you to programmatically manage pipelines, pipeline versions, experiments, runs, and other resources. You can interact with this API by using the Kubeflow Pipelines SDK, which provides a Python client library with methods for common operations.
5.1.1. REST API overview Copy linkLink copied to clipboard!
The AI Pipelines REST API is based on the Kubeflow pipelines API and provides endpoints for the following operations:
- Managing pipelines and pipeline versions
- Creating and managing experiments
- Executing and monitoring pipeline runs
- Managing artifacts and task executions
The API is exposed through the pipeline server route protected by the OpenShift AI Gateway API authentication layer. You must provide a valid access token when making API requests.
5.1.2. Kubeflow pipelines SDK Copy linkLink copied to clipboard!
The Kubeflow pipelines SDK provides a Python client library that simplifies interaction with the AI Pipelines REST API. The SDK handles request formatting, authentication, and response parsing, allowing you to focus on pipeline orchestration logic.
The SDK is based on Kubeflow Pipelines 2.0 and requires Python 3.11 or later. Before using the SDK, you must install it and authenticate the client with your pipeline server.
5.2. Installing the Kubeflow Pipelines SDK Copy linkLink copied to clipboard!
Install the Kubeflow Pipelines SDK to interact with the AI Pipelines REST API programmatically.
Prerequisites
- You have Python 3.11 or later installed in your environment.
Procedure
- Open a terminal in your environment.
Install the Kubeflow Pipelines SDK:
pip install kfp
The Kubeflow Pipelines SDK version should be compatible with the Kubeflow Pipelines version used by OpenShift AI.
Verification
Verify that the SDK is installed:
python -c "import kfp"The command outputs the installed KFP SDK version.
5.3. Working with pipelines by using the Kubeflow Pipelines SDK Copy linkLink copied to clipboard!
Use the Kubeflow Pipelines SDK to upload, list, retrieve, and delete pipelines using the REST API client. Pipelines are the core building blocks that define the workflow of your machine learning tasks.
Prerequisites
- You have installed the Kubeflow Pipelines SDK. For more information, see Installing the Kubeflow Pipelines SDK.
- You have authenticated the SDK client with your pipeline server. For more information, see Authenticating the Kubeflow Pipelines SDK with a pipeline server.
5.3.1. Uploading a pipeline Copy linkLink copied to clipboard!
Upload pipelines from local files to make them available for execution.
Use the
upload_pipelinemethod:pipeline = client.upload_pipeline( pipeline_package_path=<_path/to/pipeline.yaml_>, pipeline_name='my-pipeline', description='My sample pipeline' )where:
pipeline_package_path- Specifies the local file path to the pipeline definition file in YAML format. Replace <path/to/pipeline.yaml> with the local file path.
pipeline_name- Specifies the name for the pipeline. This name must be unique.
description- Specifies an optional description of the pipeline’s purpose.
5.3.2. Listing pipelines Copy linkLink copied to clipboard!
To retrieve a list of all pipelines with support for pagination and filtering, use the
list_pipelinesmethod:# List all pipelines pipelines = client.list_pipelines() print(f"Found {pipelines.total_size} pipelines") for pipeline in pipelines.pipelines: print(f"Pipeline: {pipeline.display_name} (ID: {pipeline.pipeline_id})")To list pipelines with pagination:
pipelines = client.list_pipelines(page_size=10, page_token=None)where:
page_size- Specifies the maximum number of pipelines to return per page.
page_token-
Specifies the token for retrieving the next page of results. Use
Nonefor the first page.
To list pipelines with filtering:
import json pipeline_filter = json.dumps({ "predicates": [{ "operation": "EQUALS", "key": "display_name", "stringValue": "my-pipeline", }] }) pipelines = client.list_pipelines(filter=pipeline_filter)where:
filter-
Specifies a JSON-serialized filter to narrow results. The filter uses predicates with operation types such as
EQUALS.
5.3.3. Getting pipeline details Copy linkLink copied to clipboard!
Retrieve detailed information about a specific pipeline by ID or name.
To get a pipeline by ID, use the
get_pipelinemethod:pipeline_id = <_pipeline_id_> pipeline = client.get_pipeline(<_pipeline_id_>)where:
pipeline_id- Specifies the unique identifier of the pipeline to retrieve. Replace <pipeline_id> with your actual value, for example, "a1b2c3d4-e5f6-7890-abcd-ef1234567890".
To get a pipeline by name:
pipeline_id = client.get_pipeline_id("my-pipeline") if pipeline_id: pipeline = client.get_pipeline(pipeline_id)
The get_pipeline_id method returns the ID for a pipeline with the specified name, which you can then use to retrieve the full pipeline details.
5.3.4. Deleting a pipeline Copy linkLink copied to clipboard!
To remove pipelines from the system by ID, use the
delete_pipelinemethod:client.delete_pipeline (<_pipeline_id_>)where:
pipeline_id-
Specifies the unique identifier of the pipeline to delete. Replace
<pipeline_id>with your actual value, for example, "a1b2c3d4-e5f6-7890-abcd-ef1234567890".
To delete a pipeline by name, first retrieve the pipeline ID:
pipeline_id = client.get_pipeline_id('my-pipeline') if pipeline_id: client.delete_pipeline(pipeline_id)
5.4. Working with pipeline versions by using the Kubeflow Pipelines SDK Copy linkLink copied to clipboard!
Use the Kubeflow Pipelines SDK to create, list, and retrieve pipeline versions programatically. Pipeline versions allow you to maintain multiple versions of the same pipeline, enabling version control and tracking of pipeline changes over time.
Prerequisites
- You have installed the Kubeflow Pipelines SDK. For more information, see Installing the Kubeflow Pipelines SDK.
- You have authenticated the SDK client with your pipeline server. For more information, see Authenticating the Kubeflow Pipelines SDK with a pipeline server.
5.4.1. Creating pipeline versions Copy linkLink copied to clipboard!
Create new versions of existing pipelines by uploading updated pipeline definitions from local files.
Use the
upload_pipeline_versionmethod:version = client.upload_pipeline_version( pipeline_package_path=<_path/to/updated-pipeline.yaml_>, pipeline_version_name="v2.0", pipeline_id="pipeline_id" )where:
pipeline_package_path-
Specifies the local file path to the updated pipeline definition file in YAML format. Replace
<path/to/updated-pipeline.yaml>with the updated pipeline definition file. pipeline_version_name- Specifies the name for the pipeline version.
pipeline_id- Specifies the unique identifier of the parent pipeline.
To upload a pipeline version from a URL, download the file locally, then use the
upload_pipeline_versionmethod:import urllib.request urllib.request.urlretrieve('https://github.com/example/pipeline-v2.yaml', 'pipeline-v2.yaml') version = client.upload_pipeline_version( pipeline_package_path='pipeline-v2.yaml', pipeline_version_name='v2.1', pipeline_id=pipeline_id )
5.4.2. Listing pipeline versions Copy linkLink copied to clipboard!
To retrieve all versions associated with a specific pipeline, use the list_pipeline_versions method:
versions = client.list_pipeline_versions(<_pipeline_id_>)
for version in versions.pipeline_versions:
print(f"Version: {version.display_name} (ID: {version.pipeline_version_id})")
where:
pipeline_id- Specifies the unique identifier of the pipeline whose versions you want to list. Replace it with your actual pipeline ID.
5.4.3. Getting pipeline version details Copy linkLink copied to clipboard!
To retrieve detailed information about a specific pipeline version, use the get_pipeline_version method:
Replace <pipeline_id> and <_pipeline_version_id> with your actual pipeline and version IDs.
version = client.get_pipeline_version(
pipeline_id=<_pipeline_id_>,
pipeline_version_id=<_pipeline_version_id_>
)
where:
pipeline_id- Specifies the unique identifier of the parent pipeline.
pipeline_version_id- Specifies the unique identifier of the pipeline version to retrieve.
5.5. Working with experiments by using the Kubeflow Pipelines SDK Copy linkLink copied to clipboard!
Use the Kubeflow Pipelines SDK to create, list, retrieve, archive, and unarchive experiments programmatically. Experiments organize and group related pipeline runs for comparison and tracking.
Prerequisites
- You have installed the Kubeflow Pipelines SDK. For more information, see Installing the Kubeflow Pipelines SDK.
- You have authenticated the SDK client with your pipeline server. For more information, see Authenticating the Kubeflow Pipelines SDK with a pipeline server.
5.5.1. Creating an experiment Copy linkLink copied to clipboard!
Create a new experiment to organize your pipeline runs into logical groups.
Use the create_experiment method:
experiment = client.create_experiment(
name="my-experiment",
description="Experiment for testing pipelines",
)
where:
name- Specifies the name for the experiment.
description- Specifies an optional description of the experiment’s purpose.
5.5.2. Listing experiments Copy linkLink copied to clipboard!
To retrieve a list of all experiments with support for pagination and sorting, use the list_experiments method:
# List all experiments
experiments = client.list_experiments()
for exp in experiments.experiments:
print(f"Experiment: {exp.display_name} (ID: {exp.experiment_id})")
# List with pagination and sorting
experiments = client.list_experiments(
page_size=20,
sort_by='created_at desc'
)
where:
page_size- Specifies the maximum number of experiments to return per page. Defaults to 10.
sort_by-
Specifies the field and order for sorting results. Use
created_at descfor newest first orname ascfor alphabetical order.
5.5.3. Getting experiment details Copy linkLink copied to clipboard!
To retrieve details for a specific experiment by ID, use the
get_experimentmethod:experiment = client.get_experiment( experiment_id=<_experiment_id_> )where:
experiment_id-
Specifies the unique identifier of the experiment to retrieve. Replace
<experiment_id>with your actual ID, for example: "a1b2c3d4-e5f6-7890-abcd-ef1234567890".
To retrieve an experiment by name:
experiment = client.get_experiment( experiment_name="my-experiment" )where:
experiment_name- Specifies the name of the experiment to retrieve.
5.6. Working with runs by using the SDK Copy linkLink copied to clipboard!
Use the Kubeflow Pipelines SDK to create, monitor, list, and manage pipeline runs programmatically. Runs represent individual executions of pipelines.
Prerequisites
- You have installed the Kubeflow Pipelines SDK. For more information, see Installing the Kubeflow Pipelines SDK.
- You have authenticated the SDK client with your pipeline server.
5.6.1. Creating and submitting runs Copy linkLink copied to clipboard!
Submit pipeline runs with parameters, either from uploaded pipelines or directly from pipeline package files.
To submit a run with parameters, use the
run_pipelinemethod:run = client.run_pipeline( experiment_id=experiment.experiment_id, job_name="my-pipeline-run", pipeline_id=pipeline_id, params={ 'learning_rate': 0.01 'epochs': 50 } )where:
experiment_id- Specifies the unique identifier of the experiment to associate with this run.
job_name- Specifies the name for the pipeline run.
pipeline_id- Specifies the unique identifier of the pipeline to execute.
params- Specifies a dictionary of parameter names and values to pass to the pipeline.
To submit a run with a specific pipeline version:
run = client.run_pipeline( experiment_id=experiment.experiment_id, job_name="my-pipeline-run-v2", pipeline_id=pipeline_id, version_id=version_id, params={'param1': 'value1'} )where:
version_id- Specifies the unique identifier of the pipeline version to execute.
To submit a run directly from a pipeline package file, use the
create_run_from_pipeline_packagemethod:run = client.create_run_from_pipeline_package( pipeline_file=<_path/to/pipeline.yaml_>, arguments={'param1': 'value1'}, run_name='direct-run', experiment_name='my-experiment' )where:
pipeline_file- Specifies the local file path to the pipeline package in YAML format.
arguments- Specifies a dictionary of parameter names and values to pass to the pipeline.
run_name- Specifies the name for the pipeline run.
experiment_name- Specifies the name of the experiment to associate with this run.
5.6.2. Monitoring runs Copy linkLink copied to clipboard!
Track the progress and status of pipeline runs, including waiting for completion.
Use the
get_runmethod to get run details:run_detail = client.get_run(run.run_id) print(f"Run status: {run_detail.state}")where:
run_id- Specifies the unique identifier of the run to retrieve.
To wait for a run to complete, use the
wait_for_run_completionmethod:client.wait_for_run_completion(run.run_id, timeout=3600) # 1 hour timeoutTo get the current run status:
run_detail = client.get_run(run.run_id) status = run_detail.state print(f"Current status: {status}")
5.6.3. Listing runs Copy linkLink copied to clipboard!
Retrieve a list of runs with support for filtering, sorting, and pagination.
To list all runs, use the
list_runsmethod:runs = client.list_runs()To list runs for a specific experiment:
runs = client.list_runs(experiment_id=experiment.experiment_id)where:
experiment_id- Specifies the unique identifier of the experiment whose runs you want to list.
To list runs with filtering, sorting, and pagination:
import json run_filter = json.dumps({ "predicates": [{ "operation": "EQUALS", "key": "state", "stringValue": "RUNNING", }] }) runs = client.list_runs( filter=run_filter, sort_by='created_at desc', page_size=50 ) for run in runs.runs: print(f"Run: {run.display_name} - Status: {run.state}")where:
filter-
Specifies a JSON-serialized filter to narrow results. The filter uses predicates with operation types such as
EQUALS. sort_by-
Specifies the field and order for sorting results. Use
created_at descfor newest first. page_size- Specifies the maximum number of runs to return per page.
5.6.4. Managing run lifecycle Copy linkLink copied to clipboard!
Control the lifecycle of runs by terminating, deleting, archiving, or unarchiving them.
To cancel a running pipeline, use the
terminate_runmethod:client.terminate_run(run.run_id)where:
run_id- Specifies the unique identifier of the run to terminate.
To delete a run, use the
delete_runmethod:client.delete_run(run.run_id)where:
run_id- Specifies the unique identifier of the run to delete.
To archive a run, use the
archive_runmethod:client.archive_run(run.run_id)where:
run_id- Specifies the unique identifier of the run to archive.
5.7. Workflow examples for the Kubeflow Pipelines SDK Copy linkLink copied to clipboard!
Use these complete workflow examples to understand how to combine Kubeflow Pipelines SDK operations into end-to-end pipeline automation workflows.
These workflow examples require the Kubeflow Pipelines SDK to be installed and authenticated with the pipeline server. For more information about how to install the Kubeflow Pipelines SDK, see Installing the Kubeflow Pipelines SDK.
5.7.1. End-to-end workflow example Copy linkLink copied to clipboard!
The following example demonstrates a complete end-to-end workflow: creating an experiment, uploading a pipeline, submitting a run, and monitoring its execution.
In the Red Hat OpenShift AI dashboard interface, experiments appear as Run groups in the Runs table. However, the REST API and SDK client use the term "experiment."
Set the PIPELINE_HOST environment variable to your pipeline server URL:
export PIPELINE_HOST=<your_pipeline_server_url>
where:
<your_pipeline_server_url>-
Specifies the URL of your AI pipelines server, for example,
https://ds-pipeline-dspa.apps.example.com.
#!/usr/bin/env python3
"""
Complete example of using AI Pipelines REST API
"""
import kfp
from kfp import Client
import time
import logging
import os
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def main():
# Initialize client
pipeline_host = os.getenv('PIPELINE_HOST')
if not pipeline_host:
raise ValueError("PIPELINE_HOST environment variable not set")
client = Client(host=pipeline_host)
try:
# 1. Create or get experiment
experiment_name = 'rest-api-example'
try:
experiment = client.get_experiment(experiment_name=experiment_name)
logger.info(f"Using existing experiment: {experiment.experiment_id}")
except:
experiment = client.create_experiment(
name=experiment_name,
description='Example experiment using REST API'
)
logger.info(f"Created new experiment: {experiment.experiment_id}")
# 2. Upload pipeline
# Replace '<path_to_pipeline_yaml>' with your compiled pipeline file path
pipeline = client.upload_pipeline(
pipeline_package_path='<path_to_pipeline_yaml>',
pipeline_name='example-pipeline',
description='Example pipeline for REST API demo'
)
logger.info(f"Uploaded pipeline: {pipeline.pipeline_id}")
# 3. Submit run
run = client.run_pipeline(
experiment_id=experiment.experiment_id,
job_name=f'example-run-{int(time.time())}',
pipeline_id=pipeline.pipeline_id,
params={
'input_data': 'gs://your-bucket/data.csv',
'model_name': 'example-model',
'epochs': 10
}
)
logger.info(f"Submitted run: {run.run_id}")
# 4. Monitor run
logger.info("Monitoring run progress...")
client.wait_for_run_completion(run.run_id, timeout=3600)
# 5. Get final results
run_detail = client.get_run(run.run_id)
final_status = run_detail.state
logger.info(f"Run completed with status: {final_status}")
if final_status.lower() == 'succeeded':
logger.info("Pipeline executed successfully!")
else:
logger.error(f"Pipeline failed with status: {final_status}")
except Exception as e:
logger.error(f"Error in pipeline execution: {str(e)}")
raise
if __name__ == '__main__':
main()
This example demonstrates the following actions:
- Initializing the SDK client
- Creating or retrieving an experiment
- Uploading a pipeline from a local YAML file
- Submitting a pipeline run with parameters
- Monitoring run completion
- Retrieving final run status
5.7.2. Example: Pagination for large result sets Copy linkLink copied to clipboard!
Implement pagination for efficient retrieval of large datasets by iterating through pages by using page tokens.
The following example demonstrates pagination for retrieving all pipelines:
def get_all_pipelines(client):
"""Efficiently retrieve all pipelines using pagination."""
all_pipelines = []
page_token = None
while True:
response = client.list_pipelines(
page_size=100,
page_token=page_token
)
all_pipelines.extend(response.pipelines)
if not response.next_page_token:
break
page_token = response.next_page_token
return all_pipelines
where:
page_size- Specifies the number of items to retrieve per page. Use a reasonable page size such as 100.
page_token- Specifies the token for retrieving the next page of results.