Project: Prefect (Orchestration & Management / Scheduling & Orchestration)
File: using-the-client.md

description: Learn how to leverage the `PrefectClient` to interact with the API. tags: client API filters orchestration Learn how to use the `PrefectClient` to interact with the API. The contains many client methods that make it simpler to do things such as: The `PrefectClient` is an async context manager, so you can use it like this: ```python hl_lines="3" from prefect import get_client async with get_client() as client: response = await client.hello() print(response.json()) # ``` To bulk reschedule flow runs that are late, delete late flow runs and create new ones in a `Scheduled` state with a delay. For example, this is useful if you accidentally scheduled many flow runs of a deployment to an inactive work pool. The following example reschedules the last three late flow runs of a deployment named `healthcheck-storage-test` to run six hours later than their original expected start time. It also deletes any remaining late flow runs of that deployment. ```python import asyncio from datetime import datetime, timedelta, timezone from typing import Optional from prefect import get_client from prefect.client.schemas.filters import ( DeploymentFilter, FlowRunFilter ) from prefect.client.schemas.objects import FlowRun from prefect.client.schemas.sorting import FlowRunSort from prefect.states import Scheduled async def reschedulelateflow_runs( deployment_name: str, delay: timedelta, mostrecentn: int, delete_remaining: bool = True, states: Optional[list[str]] = None ) -> list[FlowRun]: if not states: states = ["Late"] async with get_client() as client: flowruns = await client.readflow_runs( flowrunfilter=FlowRunFilter( state=dict(name=dict(any_=states)), expectedstarttime=dict( before_=datetime.now(timezone.utc) ), ), deployment_filter=DeploymentFilter( name={'like': deploymentname} ), sort=FlowRunSort.STARTTIMEDESC, limit=mostrecentn if not delete_remaining else None ) if not flow_runs: print(f"No flow runs found in states: {states!r}") return [] rescheduledflowruns = [] for i, run in enumerate(flow_runs): await client.deleteflowrun(flowrunid=run.id) if i < mostrecentn: newrun = await client.createflowrunfrom_deployment( deploymentid=run.deploymentid, state=Scheduled( scheduledtime=run.expectedstart_time + delay ), ) rescheduledflowruns.append(new_run) return rescheduledflowruns if name == "main": rescheduledflowruns = asyncio.run( reschedulelateflow_runs( deployment_name="healthcheck-storage-test", delay=timedelta(hours=6), mostrecentn=3, ) ) print(f"Rescheduled {len(rescheduledflowruns)} flow runs") assert all( run.state.isscheduled() for run in rescheduledflow_runs ) assert all( run.expectedstarttime >

for run in rescheduledflowruns ) ``` To get the last `N` completed flow runs from your workspace, use `readflowruns` and `prefect.client.schemas`. This example gets the last three completed flow runs from your workspace: ```python import asyncio from typing import Optional from prefect import get_client from prefect.client.schemas.filters import FlowRunFilter from prefect.client.schemas.objects import FlowRun from prefect.client.schemas.sorting import FlowRunSort async def getmostrecentflowruns( n: int = 3, states: Optional[list[str]] = None ) -> list[FlowRun]: if not states: states = ["COMPLETED"] async with get_client() as client: return await client.readflowruns( flowrunfilter=FlowRunFilter( state={'type': {'any_': states}} ), sort=FlowRunSort.ENDTIMEDESC, limit=n, ) if name == "main": last3flow_runs: list[FlowRun] = asyncio.run( getmostrecentflowruns() ) print(last3flow_runs) assert all( run.state.iscompleted() for run in last3flowruns ) assert ( endtimes := [run.endtime for run in last3flow_runs] ) == sorted(end_times, reverse=True) ``` Instead of the last three from the whole workspace, you could also use the `DeploymentFilter` like the previous example to get the last three completed flow runs of a specific deployment. Use `get_client`to set multiple runs to a `Cancelled` state. The code below cancels all flow runs that are in `Pending`, `Running`, `Scheduled`, or `Late` states when the script is run. ```python import anyio from prefect import get_client from prefect.client.schemas.filters import FlowRunFilter, FlowRunFilterState, FlowRunFilterStateName from prefect.client.schemas.objects import StateType async def listflowrunswithstates(states: list[str]): async with get_client() as client: flowruns = await client.readflow_runs( flowrunfilter=FlowRunFilter( state=FlowRunFilterState( name=FlowRunFilterStateName(any_=states) ) ) ) return flow_runs async def cancelflowruns(flow_runs): async with get_client() as client: for idx, flowrun in enumerate(flowruns): print(f"[{idx + 1}] Cancelling flow run '{flowrun.name}' with ID '{flowrun.id}'") state_updates = {} state_updates.setdefault("name", "Cancelled") state_updates.setdefault("type", StateType.CANCELLED) state = flowrun.state.copy(update=stateupdates) await client.setflowrunstate(flowrun.id, state, force=True) async def bulkcancelflow_runs(): states = ["Pending", "Running", "Scheduled", "Late"] flowruns = await listflowrunswith_states(states) while len(flow_runs) > 0: print(f"Cancelling {len(flow_runs)} flow runs\n") await cancelflowruns(flow_runs) flowruns = await listflowrunswith_states(states) print("Done!") if name == "main": anyio.run(bulkcancelflow_runs) ``` !!! tip "There are other ways to filter objects like flow runs" See for more ways to filter flow runs and other objects in your Prefect ecosystem.