Prefect Client
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
-
ModuleNotFoundError: No module named 'prefect.server'
cause `prefect-client` is a minimal client package and does not include the local Prefect server components or related modules.fixIf you need to run a local Prefect server or access server-side modules, install the full `prefect` package (`pip install prefect`). `prefect-client` is only for interacting with a remote Prefect instance. -
prefect: command not found
cause The `prefect-client` package does not include the Prefect Command Line Interface (CLI) by design, meaning `prefect` commands are not available on the system path.fixTo access the Prefect CLI for managing flows, deployments, agents, or the server, install the full `prefect` package (`pip install prefect`). -
httpx.ConnectError: [Errno 111] Connect refused | prefect.exceptions.MissingFlowError: Flow 'my-flow' not found
cause The client could not connect to the specified Prefect API URL, or the deployment/flow does not exist on the connected server. This often happens if `PREFECT_API_URL` or `PREFECT_API_KEY` are unset or incorrect, or the Prefect server is not running.fixEnsure the Prefect server is running and accessible. Verify that `PREFECT_API_URL` is set correctly to your Prefect API endpoint and `PREFECT_API_KEY` is set if authentication is required. -
RuntimeError: No active Prefect client connection. You must be in a client context to perform this action. Use `async with get_client() as client:` or ensure relevant environment variables are set.
cause An operation requiring a connection to the Prefect API was attempted outside an active client context or without the necessary environment variables (`PREFECT_API_URL`, `PREFECT_API_KEY`) to implicitly establish a connection.fixWrap your API calls within an `async with get_client() as client:` block, or ensure `PREFECT_API_URL` and `PREFECT_API_KEY` are properly configured in your environment.
Warnings
- breaking Prefect 2 (and subsequent 3.x releases, which `prefect-client` is part of) introduced significant breaking changes from Prefect 1. Flows written for Prefect 1 will not run directly on Prefect 2/3 without modification. This includes changes to API, deployment model (no more pre-registration), and core concepts.
- gotcha `prefect-client` is a minimal installation and does *not* include the Prefect CLI or local server components. Attempts to run `prefect server start` or use CLI commands will fail, and direct imports of server-related modules (e.g., `prefect.server`) will result in `ModuleNotFoundError`.
- gotcha To connect to Prefect Cloud or a remote Prefect server, `prefect-client` heavily relies on the `PREFECT_API_URL` and `PREFECT_API_KEY` environment variables. If these are not correctly configured, API interactions will fail, often with connection or authentication errors.
- gotcha Some classes, methods, or objects available for import in the full `prefect` SDK may not be 'runnable' or fully functional within `prefect-client` if they depend on server-oriented functionality (e.g., local agent execution, direct database access).
- gotcha Client and server versions should generally be compatible. While minor discrepancies might work, significant version mismatches between your `prefect-client` and the Prefect server/Cloud can lead to unexpected API errors, incorrect behavior, or features not working as intended.
Install
-
pip install prefect-client -
pip install prefect
Imports
- run_deployment
from prefect.deployments import run_deployment
- emit_event
from prefect.events import emit_event
- get_client
from prefect.client import PrefectClient
from prefect.client.orchestration import get_client
Quickstart
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())