PiAPI Task Polling and Webhooks: Handle Completion Reliably

An accepted image or video request still needs a completion workflow. For tasks using PiAPI’s Unified API, save the task ID, observe the final status, then handle the output for that model. Polling works well for a first integration; webhooks help a backend react when work finishes.
1. Save the task ID and poll with a limit
After creating a task, persist data.task_id beside your own job ID. Fetch that same task with the server-side API key. A successful HTTP response alone does not prove generation finished: inspect data.status.
curl --fail-with-body --silent --show-error \
"https://api.piapi.ai/api/v1/task/${PIAPI_TASK_ID}" \
--header "x-api-key: ${PIAPI_API_KEY}"For completed, validate the model-specific data.output; for failed, record data.error. While waiting, use bounded retries with increasing delays and jitter. Your application’s waiting deadline is a local choice: reaching it does not prove the remote task failed or was cancelled. Preserve the ID for later reconciliation.
2. Add an authenticated callback
Merge the configuration fragment below into a valid create-task body, preserving any existing config fields. Use a public HTTPS endpoint and a secret from your backend’s secret store. PiAPI documents that this secret is sent in the x-webhook-secret header; verify it before accepting a notification.
{
"config": {
"webhook_config": {
"endpoint": "https://your-app.example/piapi/callback",
"secret": "YOUR_WEBHOOK_SECRET"
}
}
}Webhook JSON contains timestamp and data. Check the task belongs to your application, then durably record or enqueue the event and return a 2xx response promptly. Run downloads and other slow work outside the HTTP handler. Treat delivery as repeatable: the docs describe retries when a successful response is not received.
3. Make polling and callbacks converge
Use one completion handler for both paths. A durable uniqueness constraint on the task ID and completion action can prevent duplicate callbacks from sending two notifications or starting two downstream jobs. A timestamp alone is not a sufficient identity across tasks. Ignore stale updates after a final state and make the worker safe to retry after a crash.
If a callback is missing or its state is unclear, fetch the saved task ID again. A fetch timeout is not a reason to blindly create another paid task. Separate transport failures from a confirmed task failure, and reconcile before deciding whether to submit again.
4. Check the failure cases
Before rollout, replay a callback, send one with the wrong secret, delay delivery, and simulate a worker restart. Verify that each completed task produces one durable result and each failed task keeps its error. Then follow the output storage guide to preserve generated files.
References: Unified API Schema, Get Task example, and Webhook documentation. Examples illustrate integration structure; they are not a live generation benchmark.


