PyHannes
07/15/2025, 8:45 AMMarvin
07/15/2025, 8:45 AMMarvin
07/15/2025, 8:46 AMpython
# Using Deployments via API
from prefect.client import get_client
async def trigger_workflow_via_api():
async with get_client() as client:
flow_run = await client.create_flow_run_from_deployment(
deployment_id="your-deployment-id",
parameters={"param1": "value1"}
)
return flow_run.id
# Using Task Workers with .delay()
from prefect import task
from fastapi import FastAPI
app = FastAPI()
@task
async def my_background_task(data):
# Your task logic here
pass
@app.post("/process")
async def process_data(data: dict):
# This will run in the background
task_run = await my_background_task.delay(data)
return {"task_id": task_run.id}
Which to Choose?
Choose Deployments via API when:
- You need full deployment features (scheduling, retries, etc.)
- You want clear separation between workflow definition and execution
- You're working in a production environment
- You need robust monitoring and tracking in the Prefect UI
Choose Task Workers with .delay() when:
- You want a simpler, more direct approach
- You're in development/testing phase
- You need quick background processing without deployment overhead
- Your tasks are relatively straightforward and don't need complex deployment configurations
Both approaches are valid, but they serve different needs. The deployment approach is more "enterprise-ready" while the task worker approach is more developer-friendly during development.
Remember that both approaches require running Prefect workers to execute the tasks - the main difference is in how you trigger and manage the execution.