Human tasks and the HTTP API

MapWorkflowEndpoints() maps the engine’s HTTP API under /api/workflow. A task list, a back office or another service uses it to start workflows, find and act on tasks, raise signals, and manage definitions. This page lists every route with its policy, and shows the requests and responses of the common calls; the HTTP API reference gives the parameters and responses of every route. The examples assume the host of Getting started on http://localhost:5090 and a token in $TOKEN.

JSON property names are camel case. Every route needs a token (Hosting): 401 without a valid token, 403 without a matching scope.

Routes

Method and pathPolicyPurpose
POST /api/workflow/startoperateStart an instance
GET /api/workflow/instancesviewList instances (filters below)
GET /api/workflow/instances/{id}viewOne instance with its tasks, events and state
GET /api/workflow/tasksviewList tasks (filters below)
GET /api/workflow/tasks/{id}viewOne task
POST /api/workflow/tasks/{id}/assignoperateAssign a task to the caller, another user or roles
POST /api/workflow/tasks/{id}/releaseoperateRelease an assigned task
POST /api/workflow/tasks/{id}/completeoperateComplete a task with a payload
POST /api/workflow/signals/raiseoperateRaise an external signal for an instance
GET /api/workflow/definitionsviewThe registered workflows
GET /api/workflow/definitions/{id}viewOne definition: the registered workflow of that name, otherwise the active stored version
GET /api/workflow/definitions/{id}/render-graphviewThe render graph of that definition, found the same way
GET /api/workflow/definitions/{name}/versionsviewThe stored versions of a workflow
POST /api/workflow/definitions/importadminStore a canonical definition, inactive
POST /api/workflow/definitions/import-multiadminStore a definition from another format
POST /api/workflow/definitions/exportviewExport a stored definition
POST /api/workflow/definitions/export-multiviewExport a stored definition in a format
POST /api/workflow/definitions/{name}/activateadminActivate a stored version
GET /api/workflow/supported-formatsviewThe formats of the multi-format import and export
GET /api/workflow/diagrams/{name}viewA diagram of a registered workflow
GET /api/workflow/canonical/schemaviewThe JSON Schema of canonical definitions
POST /api/workflow/canonical/validateviewValidate a canonical definition
GET /api/workflow/functionsviewThe installed expression functions
GET /api/workflow/metadataviewThe application name (IHostEnvironment.ApplicationName), the diagram provider and the inspection features
POST /api/workflow/retention/runadminRun the retention once
GET /api/workflow/signals/dead-lettersviewList dead-lettered signals
POST /api/workflow/signals/dead-letters/replayadminReplay dead-lettered signals
GET /api/workflow/signals/pump/statsviewSignal pump counters
GET /api/workflow/designated-workflowsviewThe Designated Workflow ledger and its count (Licensing)

Policies: view = workflow:view, workflow:operate or workflow:admin; operate = workflow:operate or workflow:admin; admin = workflow:admin.

Refusals

A request the engine refuses for an expected reason answers with the status of the refusal and a body that names it in error and describes it in message:

{ "error": "WorkflowTaskActionDenied", "message": "<the reason>" }
Statuserror
404WorkflowDefinitionNotFound, WorkflowInstanceNotFound, WorkflowTaskNotFound, WORKFLOW_DEFINITION_NOT_FOUND
403WorkflowTaskActionDenied, WorkflowServiceAudienceDenied, WorkflowActorUnresolved
409WorkflowTaskAlreadyCompleted, WorkflowTaskExpired, WorkflowTaskCancelled, WorkflowStartExactReplayConflict, WorkflowStartNotReady, WorkflowOperationNotSupported; the definition conflicts WORKFLOW_DEFINITION_ACTIVATION_FENCE_LOST, WORKFLOW_DEFINITION_IMMUTABLE_CONFLICT, WORKFLOW_DEFINITION_VERSION_HASH_CONFLICT, WORKFLOW_DEFINITION_ORIGIN_COLLISION, WORKFLOW_MANAGED_DEFINITION_GOVERNANCE_REQUIRED, WORKFLOW_DEFINITION_ROLLBACK_NOT_AUTHORIZED
400WorkflowBusinessIdMissing, WorkflowPayloadFieldMissing, WorkflowSortColumnNotAllowed, WorkflowArbitrarySignalNotAllowed; the definition errors WORKFLOW_DEFINITION_ROLLBACK_TARGET_INVALID, WORKFLOW_DEFINITION_ORIGIN_INVALID, WORKFLOW_DEFINITION_HASH_INVALID, WORKFLOW_MANAGED_DEFINITION_HASH_REQUIRED
502WorkflowTransportFailed: a service call the workflow made during the request failed
500WorkflowRuntimeFailed

Another engine refusal answers with the status the engine gives it, 400 by default. Any other error answers 500 without this body.

Start an instance

curl -s -X POST http://localhost:5090/api/workflow/start \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d '{"workflowName":"OrderApproval","payload":{"orderId":"ORD-1002","customer":"Contoso","amount":900.0}}'
Request fieldRequiredMeaning
workflowNameyesThe registered workflow
workflowVersionnoA registered version; the latest registered version when absent
payloadnoThe start request, bound to the workflow’s start request type
businessReferencenokey and parts; overrides the business key of the start request
deduplicationno"OpenBusinessKey": return the open instance with the same workflow and business key instead of starting a second one (the response then has "deduplicated": true); "None" (the default) always starts a new instance

The response carries the workflowInstanceId, the resolved name and version, the business reference, the tasks the start opened (nextTasks) and the workflowState. A start of a workflow this host does not register answers 404 with error: WorkflowDefinitionNotFound (Refusals).

Find tasks

curl -s "http://localhost:5090/api/workflow/tasks?status=Open&workflowName=OrderApproval" \
  -H "Authorization: Bearer $TOKEN"
Filter (query)Matches
workflowName, workflowVersionThe workflow
workflowInstanceIdOne instance
businessReferenceKeyThe business key, for example ORD-1002
assigneeThe assigned user
statusOpen, Assigned, Completed, Expired, Cancelled, Stale

Each task’s allowedActions are computed for the authenticated caller; an actorId query parameter is ignored, here and on GET /api/workflow/tasks/{id} and GET /api/workflow/instances/{id}.

GET /api/workflow/instances takes workflowName, workflowVersion, workflowInstanceId, businessReferenceKey, status (Open, Completed, Stale) and includeDetails (adds the active task and the state of each instance).

A task summary carries the workflowTaskId, taskName, taskType, route, status, assignee, the roles (workflowRoles, taskRoles, runtimeRoles, effectiveRoles), allowedActions, the payload, the business reference, createdOnUtc, completedOnUtc, staleAfterUtc, purgeAfterUtc and, for a task with a deadline, deadlineUtc.

Act on a task

Complete:

curl -s -X POST http://localhost:5090/api/workflow/tasks/$TASK_ID/complete \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d '{"payload":{"decision":"approve"}}'

The payload is the task’s answer; the task’s OnComplete steps read it as payload.*. The response has completed, the instance id, the tasks the completion opened (nextTasks) and the state.

Assign to oneself (an empty body or none), to another user (targetUserId) or to roles (targetRoles), and release (no body):

curl -s -X POST http://localhost:5090/api/workflow/tasks/$TASK_ID/assign \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" -d '{}'

curl -s -X POST http://localhost:5090/api/workflow/tasks/$TASK_ID/assign \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d '{"targetRoles":["finance"]}'

curl -s -X POST http://localhost:5090/api/workflow/tasks/$TASK_ID/release \
  -H "Authorization: Bearer $TOKEN"

The route names the task, and the action acts as the caller: the actor ID and the roles come from the token (Hosting). The bodies are optional: complete takes payload, assign takes targetUserId or targetRoles, and release takes none. A body that also sends workflowTaskId, actorId or actorRoles is accepted, and those members are not used.

Who may act on a task

A task’s effective roles are the runtime roles of ActivateTask(name, rolesExpression) when the expression gave any; otherwise the task roles when the task has any; otherwise the workflow roles. The default permission evaluator decides:

ActionAllowed for
Assign to oneselfAn actor with one of the effective roles
Assign to another user, assign to rolesAn administrator
ReleaseThe current assignee, or an administrator
CompleteAn actor with one of the effective roles, or an administrator; with AssigneeCanComplete, also the current assignee

Administrators are the actors with a role in GenericAssignmentPermissions:AdminRoles:

{ "GenericAssignmentPermissions": { "AdminRoles": [ "workflow-admin" ], "AssigneeCanComplete": false } }

A refused action leaves the task unchanged and answers 403 with error: WorkflowTaskActionDenied and the reason in message. To apply other rules, register your own IWorkflowAssignmentPermissionEvaluator.

Raise a signal

curl -s -X POST http://localhost:5090/api/workflow/signals/raise \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d '{"workflowInstanceId":"<instance id>","signalName":"documents-uploaded","payload":{"count":3}}'

The instance waiting in WaitForSignal("...", "documents-uploaded", resultKey: "documents") resumes, and result.documents.count is 3. The response has the signalId and queued; the signal pump delivers the signal. An instance run by a runtime provider without durable signals, such as Stella.InProcess, refuses the signal with 409 WorkflowOperationNotSupported.

Definitions

GET /api/workflow/definitions lists the workflows registered in code, with their versions, display names, roles and tasks. The store-backed routes work on imported definitions; the file is a canonical definition, here the workflow of lesson 2 of the tutorials written with the export helper of Canonical definitions:

curl -s -X POST http://localhost:5090/api/workflow/definitions/import \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d "{\"canonicalDefinitionJson\": $(jq -Rs . < InventoryRestock.definition.json)}"

The import answers with workflowName, version, contentHash, wasImported, wasNewVersion, isActive and validationIssues. A new version is stored inactive; importing content that is already stored changes nothing and answers with the stored version’s isActive. The audit records the token’s actor as the importer; an importedBy in the body is not used. Activation, rollback and the audit are described in Governed activation and publishing.

Diagrams

GET /api/workflow/diagrams/{name} returns the positioned diagram of a registered workflow; the query parameters workflowVersion, workflowInstanceId (highlights the instance’s progress), layoutProvider, layoutEffort, layoutOrderingIterations and layoutPlacementIterations adjust it (Rendering).

Operations

POST /api/workflow/retention/run runs the retention once. The body is {} or takes:

FieldEffect
referenceUtcThe time the retention compares the stored dates with, instead of now
runningOlderThanDaysMarks open instances created more than this many days ago as stale and purges them, whatever their stored dates
completedOlderThanDaysPurges completed instances completed more than this many days ago, whatever their stored dates

Both day fields delete data that the scheduled retention would keep; use them with care. GET /api/workflow/signals/dead-letters and POST .../replay manage dead letters; GET /api/workflow/signals/pump/stats returns the pump counters (Operations).

Calling the engine in process

A worker host, a message handler or a test calls the same operations through WorkflowRuntimeService, resolved from a scope:

[Test]
public async Task AChangeRequestOpensTheRevisionTaskAndTheRevisionReturnsToTheReviewer()
{
    using var scope = host!.Services.CreateScope();
    var runtime = scope.ServiceProvider.GetRequiredService<WorkflowRuntimeService>();

    var started = await runtime.StartWorkflowAsync(new StartWorkflowRequest
    {
        WorkflowName = "DocumentReview",
        Payload = new Dictionary<string, object?> { ["documentId"] = "DOC-7", ["title"] = "Travel policy", ["author"] = "author-1" },
    });
    Assert.That(started.NextTasks.Select(task => task.TaskName), Is.EqualTo(new[] { "Review document" }));

    var changes = await runtime.CompleteTaskAsync(new WorkflowTaskCompleteRequest
    {
        WorkflowTaskId = started.NextTasks.Single().WorkflowTaskId,
        ActorId = "reviewer-1",
        ActorRoles = ["reviewer"],
        Payload = new Dictionary<string, object?> { ["decision"] = "changes", ["comments"] = "Add the approval limits." },
    });
    Assert.That(changes.NextTasks.Select(task => task.TaskName), Is.EqualTo(new[] { "Revise document" }));

    var revised = await runtime.CompleteTaskAsync(new WorkflowTaskCompleteRequest
    {
        WorkflowTaskId = changes.NextTasks.Single().WorkflowTaskId,
        ActorId = "author-1",
        ActorRoles = ["author"],
    });
    Assert.That(revised.NextTasks.Select(task => task.TaskName), Is.EqualTo(new[] { "Review document" }));
    Assert.That(revised.WorkflowState["revision"]?.ToString(), Is.EqualTo("2"));
}

The in-process calls skip the HTTP authorization: the actor and roles you pass are used as given. Check the caller’s rights before you call.

An OpenAPI document of your host

To publish an OpenAPI document of your own host, add the ASP.NET Core OpenAPI services to it: the endpoints carry their request and response types and their refusal answers.

Pitfalls