Complete task
This endpoint marks a task as complete. The exact endpoint and payload structure differ slightly depending on whether it’s a task within a process run or a one-off task:
- Process Task:
POST /organizations/{org_id}/runs/{run_id}/completed-tasks
- One-off Task:
POST /organizations/{org_id}/completed-tasks
Replace {org_id}
, {run_id}
(if applicable) with the appropriate IDs.
Authorization: Bearer {your_access_token}
Accept: application/json
X-Tallyfy-Client: APIClient
Content-Type: application/json
The request body requires a JSON object specifying the task to complete.
Common Fields:
task_id
(string, required): The ID of the task to mark as complete.is_approved
(boolean, optional): Relevant for approval tasks, set totrue
to approve,false
to reject.taskdata
(object, optional): You can optionally provide final form field values within ataskdata
object simultaneously with completing the task (same structure as in Update Task ↗).
Example Body (Simple Completion):
{ "task_id": "TASK_ID_TO_COMPLETE"}
Example Body (Completion with Final Field Update):
{ "task_id": "TASK_ID_TO_COMPLETE", "taskdata": { "final_notes_field_id": "All checks passed." }}
Example Body (Approval Task - Approve):
{ "task_id": "APPROVAL_TASK_ID", "is_approved": true}
(Examples use the endpoint for process tasks. Adapt the URL and potentially the payload structure slightly for one-off tasks if needed, based on Swagger definitions #definitions/CompletedProcessTask
vs the one for one-off tasks).
const accessToken = 'YOUR_PERSONAL_ACCESS_TOKEN';const orgId = 'YOUR_ORGANIZATION_ID';const runId = 'PROCESS_RUN_ID'; // Set to null or omit for one-off tasksconst taskId = 'TASK_ID_TO_COMPLETE'; // Required
// Construct API URL based on whether it's a process task or one-off taskconst apiUrl = runId ? `https://go.tallyfy.com/api/organizations/${orgId}/runs/${runId}/completed-tasks` : `https://go.tallyfy.com/api/organizations/${orgId}/completed-tasks`;
const completePayload = { task_id: taskId, // Required // Example: Completing an approval task (approve) // is_approved: true, // Example: Adding a final note while completing // taskdata: { // "notes_field_id": "Task completed via API." // }};
const headers = new Headers();headers.append('Authorization', `Bearer ${accessToken}`);headers.append('Accept', 'application/json');headers.append('X-Tallyfy-Client', 'APIClient');headers.append('Content-Type', 'application/json');
fetch(apiUrl, { method: 'POST', headers: headers, body: JSON.stringify(completePayload)}).then(response => { return response.json().then(data => { // Attempt to parse JSON regardless of status if (!response.ok) { console.error(`Failed to complete task ${taskId}:`, data); throw new Error(`HTTP error! status: ${response.status}`); } // Check for 200 OK or 201 Created console.log(`Task completion request successful for ${taskId}. Status: ${response.status}`); return data; // Pass successful data along });}).then(data => { console.log('Completed task details:'); console.log(JSON.stringify(data, null, 2));}).catch(error => { console.error(`Error completing task ${taskId}:`, error.message);});
import requestsimport jsonimport os
access_token = os.environ.get('TALLYFY_ACCESS_TOKEN', 'YOUR_PERSONAL_ACCESS_TOKEN')org_id = os.environ.get('TALLYFY_ORG_ID', 'YOUR_ORGANIZATION_ID')run_id = os.environ.get('TALLYFY_RUN_ID') # Get from env, could be None for one-off tasktask_id = 'TASK_ID_TO_COMPLETE' # Required
# Construct API URL based on whether run_id existsif run_id: api_url = f'https://go.tallyfy.com/api/organizations/{org_id}/runs/{run_id}/completed-tasks'else: api_url = f'https://go.tallyfy.com/api/organizations/{org_id}/completed-tasks'
headers = { 'Authorization': f'Bearer {access_token}', 'Accept': 'application/json', 'X-Tallyfy-Client': 'APIClient', 'Content-Type': 'application/json'}
complete_payload = { 'task_id': task_id, # Required # Example: Reject an approval task # 'is_approved': False, # Example: Update a field simultaneously # 'taskdata': { # 'status_field_id': 'Complete' # }}
response = Nonetry: response = requests.post(api_url, headers=headers, json=complete_payload) response.raise_for_status() # Raises HTTPError for bad responses (4xx or 5xx)
completed_task_data = response.json() print(f'Successfully completed task {task_id}:') print(json.dumps(completed_task_data, indent=4))
except requests.exceptions.HTTPError as http_err: error_details = "" try: if response is not None: error_details = response.json() except json.JSONDecodeError: if response is not None: error_details = response.text print(f"HTTP error occurred completing task {task_id}: {http_err}") print(f"Response Body: {error_details}")except requests.exceptions.RequestException as req_err: print(f"Request failed completing task {task_id}: {req_err}")except json.JSONDecodeError: print(f"Failed to decode successful JSON response for task {task_id} completion") if response is not None: print(f"Response Text: {response.text}")except Exception as err: print(f"An unexpected error occurred: {err}")
import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.io.IOException;// Requires a JSON library like Jackson or Gson// import com.fasterxml.jackson.databind.ObjectMapper;// import java.util.Map;// import java.util.HashMap;
public class CompleteTask { public static void main(String[] args) { String accessToken = System.getenv().getOrDefault("TALLYFY_ACCESS_TOKEN", "YOUR_PERSONAL_ACCESS_TOKEN"); String orgId = System.getenv().getOrDefault("TALLYFY_ORG_ID", "YOUR_ORGANIZATION_ID"); String runId = System.getenv("TALLYFY_RUN_ID"); // Get from env, might be null for one-off task String taskId = "TASK_ID_TO_COMPLETE"; // Required
String apiUrl; if (runId != null && !runId.isEmpty()) { apiUrl = String.format("https://go.tallyfy.com/api/organizations/%s/runs/%s/completed-tasks", orgId, runId); } else { apiUrl = String.format("https://go.tallyfy.com/api/organizations/%s/completed-tasks", orgId); }
// --- Payload Construction --- // Using Jackson/Gson recommended: /* ObjectMapper mapper = new ObjectMapper(); Map<String, Object> payload = new HashMap<>(); payload.put("task_id", taskId); // Required // payload.put("is_approved", true); // Optional for approval tasks // Map<String, String> taskData = Map.of("final_notes", "Completed via Java"); // payload.put("taskdata", taskData); // Optional String jsonPayload; try { jsonPayload = mapper.writeValueAsString(payload); } catch (Exception e) { System.err.println("Failed to serialize JSON: " + e.getMessage()); return; } */ // Simple manual JSON string: String jsonPayload = String.format("{\"task_id\": \"%s\"}", taskId); // --- End Payload ---
HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(apiUrl)) .header("Authorization", "Bearer " + accessToken) .header("Accept", "application/json") .header("X-Tallyfy-Client", "APIClient") .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(jsonPayload)) .build();
try { HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 200 || response.statusCode() == 201) { // Check for 200 OK or 201 Created System.out.println("Successfully completed task " + taskId + ":"); System.out.println(response.body()); // TODO: Consider parsing the JSON response } else { System.err.println("Failed to complete task " + taskId + ". Status: " + response.statusCode()); System.err.println("Response Body: " + response.body()); } } catch (IOException | InterruptedException e) { System.err.println("Request failed: " + e.getMessage()); Thread.currentThread().interrupt(); } catch (Exception e) { System.err.println("An unexpected error occurred: " + e.getMessage()); e.printStackTrace(); } }}
package main
import ( "bytes" "encoding/json" "fmt" "io/ioutil" "net/http" "os" "time")
func main() { accessToken := os.Getenv("TALLYFY_ACCESS_TOKEN") if accessToken == "" { accessToken = "YOUR_PERSONAL_ACCESS_TOKEN" } orgId := os.Getenv("TALLYFY_ORG_ID") if orgId == "" { orgId = "YOUR_ORGANIZATION_ID" } runId := os.Getenv("TALLYFY_RUN_ID") // Get from env, might be "" for one-off task taskId := "TASK_ID_TO_COMPLETE" // Required
var apiUrl string if runId != "" { apiUrl = fmt.Sprintf("https://go.tallyfy.com/api/organizations/%s/runs/%s/completed-tasks", orgId, runId) } else { apiUrl = fmt.Sprintf("https://go.tallyfy.com/api/organizations/%s/completed-tasks", orgId) }
payloadData := map[string]interface{}{ "task_id": taskId, // Required // "is_approved": true, // Optional for approval tasks // "taskdata": map[string]interface{} { // Optional // "some_field_id": "final value", // }, }
jsonData, err := json.Marshal(payloadData) if err != nil { fmt.Printf("Error marshalling JSON: %v\n", err) return }
client := &http.Client{Timeout: 15 * time.Second} req, err := http.NewRequest(http.MethodPost, apiUrl, bytes.NewBuffer(jsonData)) if err != nil { fmt.Printf("Error creating complete task request for task %s: %v\n", taskId, err) return }
req.Header.Set("Authorization", "Bearer "+accessToken) req.Header.Set("Accept", "application/json") req.Header.Set("X-Tallyfy-Client", "APIClient") req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req) if err != nil { fmt.Printf("Error executing complete task request for task %s: %v\n", taskId, err) return } defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Printf("Error reading complete task response body for task %s: %v\n", taskId, err) return }
// API might return 201 Created if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated { fmt.Printf("Failed to complete task %s. Status: %d\nBody: %s\n", taskId, resp.StatusCode, string(body)) return }
fmt.Printf("Successfully completed task %s:\n", taskId) // Pretty print JSON response var prettyJSON bytes.Buffer if err := json.Indent(&prettyJSON, body, "", " "); err == nil { fmt.Println(prettyJSON.String()) } else { fmt.Println(string(body)) } // TODO: Unmarshal JSON if needed}
#include <iostream>#include <string>#include <optional> // For optional runId#include <cpprest/http_client.h>#include <cpprest/json.h>
using namespace web;using namespace web::http;using namespace web::http::client;using namespace web::json;
pplx::task<void> CompleteTallyfyTask(const utility::string_t& taskId, std::optional<utility::string_t> runId = std::nullopt, const value& payload = value::null()){ utility::string_t accessToken = U("YOUR_PERSONAL_ACCESS_TOKEN"); utility::string_t orgId = U("YOUR_ORGANIZATION_ID");
utility::string_t apiUrlBase = U("https://go.tallyfy.com/api/organizations/") + orgId; utility::string_t apiUrl;
if (runId) { apiUrl = apiUrlBase + U("/runs/") + runId.value() + U("/completed-tasks"); } else { apiUrl = apiUrlBase + U("/completed-tasks"); }
// Construct payload - ensure task_id is always present value finalPayload = payload; if (finalPayload.is_null()) { finalPayload = value::object(); } if (!finalPayload.has_field(U("task_id"))) { finalPayload[U("task_id")] = value::string(taskId); } // Ensure task_id in payload matches the one passed to function if both exist if (finalPayload.has_field(U("task_id")) && finalPayload[U("task_id")].as_string() != taskId) { std::wcerr << L"Warning: task_id in payload differs from function argument." << std::endl; finalPayload[U("task_id")] = value::string(taskId); // Prioritize function argument }
http_client client(apiUrl); http_request request(methods::POST);
request.headers().add(U("Authorization"), U("Bearer ") + accessToken); request.headers().add(U("Accept"), U("application/json")); request.headers().add(U("X-Tallyfy-Client"), U("APIClient")); request.headers().set_content_type(U("application/json")); request.set_body(finalPayload);
return client.request(request).then([taskId](http_response response) { utility::string_t taskIdW = taskId; return response.extract_json().then([response, taskIdW](pplx::task<value> task) { try { value const & body = task.get(); // API might return 201 Created if (response.status_code() == status_codes::OK || response.status_code() == status_codes::Created) { std::wcout << L"Successfully completed task " << taskIdW << L":\n" << body.serialize() << std::endl; } else { std::wcerr << L"Failed to complete task " << taskIdW << L". Status: " << response.status_code() << L"\nResponse: " << body.serialize() << std::endl; } } catch (const http_exception& e) { std::wcerr << L"HTTP exception during complete task: " << e.what() << std::endl; } catch (const std::exception& e) { std::wcerr << L"Exception during complete task response handling: " << e.what() << std::endl; } }); });}
int main() { try { // Example 1: Complete a process task value payload1 = value::object(); // Optional payload CompleteTallyfyTask(U("TASK_ID_1"), U("RUN_ID_1"), payload1).wait();
// Example 2: Complete a one-off task CompleteTallyfyTask(U("ONEOFF_TASK_ID")).wait();
// Example 3: Complete & update taskdata value payload3 = value::object(); value taskdata = value::object(); taskdata[U("field_abc")] = value::string(U("Final C++ notes")); payload3[U("taskdata")] = taskdata; CompleteTallyfyTask(U("TASK_ID_2"), U("RUN_ID_2"), payload3).wait();
} catch (const std::exception &e) { std::cerr << "Error in main: " << e.what() << std::endl; } return 0;}// Requires C++ REST SDK (Casablanca)
using System;using System.Collections.Generic;using System.Net.Http;using System.Net.Http.Headers;using System.Text;using System.Text.Json;using System.Text.Json.Serialization; // For JsonIgnoreConditionusing System.Threading.Tasks;
public class TallyfyTaskCompleter{ private static readonly HttpClient client = new HttpClient();
public class CompleteTaskPayload { [JsonPropertyName("task_id")] public string TaskId { get; set; } // Required
[JsonPropertyName("is_approved")] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public bool? IsApproved { get; set; } // Optional for approval tasks
[JsonPropertyName("taskdata")] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public Dictionary<string, object> TaskData { get; set; } // Optional for field updates }
// Use runId = null for one-off tasks public static async Task CompleteTaskAsync(string taskId, string runId, CompleteTaskPayload payload = null) { var accessToken = Environment.GetEnvironmentVariable("TALLYFY_ACCESS_TOKEN") ?? "YOUR_PERSONAL_ACCESS_TOKEN"; var orgId = Environment.GetEnvironmentVariable("TALLYFY_ORG_ID") ?? "YOUR_ORGANIZATION_ID";
string apiUrl; if (!string.IsNullOrEmpty(runId)) { apiUrl = $"https://go.tallyfy.com/api/organizations/{orgId}/runs/{runId}/completed-tasks"; } else { apiUrl = $"https://go.tallyfy.com/api/organizations/{orgId}/completed-tasks"; }
// Ensure payload has task_id if (payload == null) { payload = new CompleteTaskPayload(); } payload.TaskId = taskId; // Set or overwrite task_id from parameter
try { using var request = new HttpRequestMessage(HttpMethod.Post, apiUrl); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); request.Headers.Add("X-Tallyfy-Client", "APIClient");
// Serialize payload, ignore nulls var options = new JsonSerializerOptions { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull }; string jsonPayload = JsonSerializer.Serialize(payload, options); request.Content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.SendAsync(request); string responseBody = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode) // Check for 200 OK or 201 Created { Console.WriteLine($"Successfully completed task {taskId}. Status: {response.StatusCode}"); try { using var doc = JsonDocument.Parse(responseBody); Console.WriteLine(JsonSerializer.Serialize(doc.RootElement, new JsonSerializerOptions { WriteIndented = true })); } catch (JsonException) { Console.WriteLine(responseBody); } } else { Console.WriteLine($"Failed to complete task {taskId}. Status: {response.StatusCode}"); Console.WriteLine($"Response: {responseBody}"); } } catch (HttpRequestException e) { Console.WriteLine($"Request Exception completing task {taskId}: {e.Message}"); } catch (JsonException jsonEx) { Console.WriteLine($"JSON Serialization/Parsing Error: {jsonEx.Message}"); } catch (Exception ex) { Console.WriteLine($"An unexpected error occurred: {ex.Message}"); } }
// Example Usage: // static async Task Main(string[] args) // { // // Complete a process task // await CompleteTaskAsync("PROCESS_TASK_ID", "RUN_ID", new CompleteTaskPayload()); // // // Complete a one-off task // await CompleteTaskAsync("ONE_OFF_TASK_ID", null);
// // Complete and update a field // var payload = new CompleteTaskPayload { // TaskData = new Dictionary<string, object> { { "field_abc", "Final C# Value" } } // }; // await CompleteTaskAsync("TASK_ID_3", "RUN_ID_3", payload); // }}
A successful request returns a 200 OK
status code and a JSON object containing the details of the task, now marked as complete.
{ "data": { "id": "TASK_ID_TO_COMPLETE", "title": "Review Proposal", "status": "completed", // Status is now complete "completed_at": "2024-05-20T17:00:00.000Z", // Completion timestamp "completer_id": 1001, // User who completed the task (via API token) // ... other task properties, potentially including updated taskdata ... // For process tasks, may include 'tasks_changed_by_rules' if completion triggered rules "tasks_changed_by_rules": {} }}
If the task cannot be completed (e.g., already complete, permissions issue, invalid ID), an appropriate error status code will be returned.
- 2025 Tallyfy, Inc.
- Privacy Policy
- Terms of Use
- Report Issue
- Trademarks