This guide walks you through the complete workflow of triggering a copy.ai workflow run via the API and polling for the result.
Step 1: Initiate run
Trigger the workflow run
let api_key = "[API key goes here]";
let workflow_id = "[workflow uuid goes here]";
let workflow_url = 'https://api.copy.ai/api/workflow/'+ workflow_id + '/run';
let input_data = {
"startVariables": {
"<key>":"<input variables would go here>"
},
"metadata": {
"<key>":"<any meta data here>"
}
};
const options = {
method: 'POST',
headers: {"Content-Type": 'application/json', 'x-copy-ai-api-key': api_key },
body:JSON.stringify(input_data)
};
let run = await fetch(workflow_url, options)
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error(err));Step 2: Poll for result
Once you initiate a run, you can poll for the response with the given run id.
let run_id = run.data.id;
let run_url = 'https://api.copy.ai/api/workflow/'+ workflow_id + '/run/' + run_id;
const poll_options = {
method: 'GET',
headers: {"Content-Type": 'application/json', 'x-copy-ai-api-key': api_key },
};
let result = await fetch(workflow_url, options)
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error(err));Full Code
let api_key = "[API key goes here]";
let workflow_id = "[workflow uuid goes here]";
let workflow_url = 'https://api.copy.ai/api/workflow/'+ workflow_id + '/run';
let input_data = {
"startVariables": {
"<key>":"<input variables would go here>"
},
"metadata": {
"<key>":"<any meta data here>"
}
};
const options = {
method: 'POST',
headers: {"Content-Type": 'application/json', 'x-copy-ai-api-key': api_key },
body:JSON.stringify(input_data)
};
let run = await fetch(workflow_url, options)
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error(err));
let run_id = run.data.id;
let run_url = 'https://api.copy.ai/api/workflow/'+ workflow_id + '/run/' + run_id;
const poll_options = {
method: 'GET',
headers: {"Content-Type": 'application/json', 'x-copy-ai-api-key': api_key },
};
let result = await fetch(workflow_url, options)
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error(err));Expected response
//Response from initial trigger
{
"status": "success",
"data": {
"id": "<workflow run id>"
}
}
//Response from polling
{
"status": "success",
"data":
{
"id": "<workflow run id>",
"input":
{
...
},
"status": "PROCESSING",
"output":
{
...
},
"createdAt": "2022-11-18T20:30:07.434Z"
}
}