Prefect Client

3.6.26 · active · verified Thu Apr 16

Prefect Client is a lightweight Python library providing essential client-side functionality for interacting with Prefect Cloud or a self-hosted Prefect server instance. It's designed for ephemeral execution environments like AWS Lambda, omitting the full Prefect SDK's CLI and local server components. The current version is 3.6.26, and it follows the active release cadence of the main Prefect project, including frequent stable and nightly builds.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `prefect-client` to interact with a remote Prefect server or Prefect Cloud. It shows how to trigger a deployed flow and how to query the API for existing deployments. Ensure the `PREFECT_API_URL` and `PREFECT_API_KEY` environment variables are set for successful connection to your Prefect instance.

import os
import asyncio
from prefect.deployments import run_deployment
from prefect.client.orchestration import get_client

# Ensure API URL and Key are set as environment variables for remote connection
os.environ['PREFECT_API_URL'] = os.environ.get('PREFECT_API_URL', 'http://localhost:4200/api')
os.environ['PREFECT_API_KEY'] = os.environ.get('PREFECT_API_KEY', 'your_api_key_if_needed')

async def interact_with_prefect_api():
    print(f"Connecting to Prefect API at: {os.environ['PREFECT_API_URL']}")
    async with get_client() as client:
        # Example 1: Remotely trigger a deployment
        try:
            flow_run = await run_deployment(
                name="my-flow/my-deployment",
                parameters={"message": "Hello from prefect-client!"},
                timeout=0 # Do not wait for the flow run to complete
            )
            print(f"Triggered flow run: {flow_run.name} (ID: {flow_run.id})")
        except Exception as e:
            print(f"Could not trigger deployment: {e}. Ensure 'my-flow/my-deployment' exists and is accessible.")

        # Example 2: Read some information from the API
        try:
            deployments = await client.read_deployments(limit=5)
            print(f"\nFound {len(deployments)} deployments:")
            for dep in deployments:
                print(f"  - {dep.name} (ID: {dep.id})")
        except Exception as e:
            print(f"Could not read deployments: {e}. Check API URL/Key and server status.")

if __name__ == "__main__":
    # Note: If connecting to Prefect Cloud, ensure PREFECT_API_KEY is set
    # os.environ['PREFECT_API_KEY'] = 'your_prefect_cloud_api_key'
    asyncio.run(interact_with_prefect_api())

view raw JSON →