Synchronous vs Asynchronous Predictions
The Kanva API supports both synchronous and asynchronous prediction modes to accommodate different use cases.
Synchronous Mode
Use ?sync=true to wait for the prediction to complete:
response = requests.post(
f"{API_URL}/projects/{PROJECT_ID}/predict",
headers={"X-API-Key": API_KEY, "Content-Type": "application/json"},
json={"input": data},
params={"sync": "true", "timeout": "60"}
)
result = response.json()
predictions = result["data"]["predictions"]
When to Use Sync Mode
- Quick predictions (under 60 seconds)
- Interactive applications requiring immediate results
- Simple integrations without polling infrastructure
Timeout Behavior
The timeout parameter (default: 60 seconds) controls how long to wait:
- If prediction completes within timeout: returns results directly
- If timeout exceeded: returns 408 Request Timeout
Asynchronous Mode
Without sync=true, the API returns immediately with a job ID:
# Start the job
response = requests.post(
f"{API_URL}/projects/{PROJECT_ID}/predict",
headers={"X-API-Key": API_KEY, "Content-Type": "application/json"},
json={"input": data}
)
job_id = response.json()["data"]["jobId"]
# Poll for results
while True:
status = requests.get(
f"{API_URL}/projects/{PROJECT_ID}/jobs/{job_id}",
headers={"X-API-Key": API_KEY}
).json()
if status["data"]["status"] == "completed":
predictions = status["data"]["result"]["predictions"]
break
elif status["data"]["status"] == "failed":
raise Exception(status["data"]["error"])
time.sleep(2)
When to Use Async Mode
- Long-running predictions
- Batch processing
- When you need webhook notifications
- Systems with job queue architectures
Using Webhooks
Instead of polling, configure a webhook to receive results automatically:
response = requests.post(
f"{API_URL}/projects/{PROJECT_ID}/predict",
headers={"X-API-Key": API_KEY, "Content-Type": "application/json"},
json={
"input": data,
"webhookUrl": "https://your-server.com/webhook",
"webhookSecret": "your_secret"
}
)
Learn more: Webhooks