Skip to content

Create a Work Item and Send It to a Workflow

An accounts payable team receives invoices in a shared mailbox that its own service already reads. It wants each invoice to land in KnowledgeLake with the vendor and invoice number set, and to start the invoice approval workflow, with no one uploading by hand.

At a glance

  • Extension point REST API from your own code
  • You need A token with Manage Work Items and Manage Workflows; an active workflow named Invoice Approval; content type fields Vendor and InvoiceNumber
  • Teaches The three-call intake pattern (create, add, send), and why the order matters
graph LR
    A["Your service"] -->|"1. NewWorkItem"| B["Empty work item"]
    A -->|"2. AddDocument, one call per file"| B
    A -->|"3. SendToWorkflow"| C["Invoice Approval workflow"]
    B --> C

Set it up

  1. Create a service account and give it the Manage Work Items and Manage Workflows API features in Configuration > Permissions > API Access. Give it Run permission on the Invoice Approval workflow.
  2. Sign in as the service account and create a token with those two features in Configuration > Services > API Access. See Authentication.
  3. Set two environment variables where the program runs: KnowledgeLakeApiURL (for example https://yourcompany.knowledgelake.io/api) and KnowledgeLakeApiToken.
  4. Generate KL.APIClient from your tenant's spec and reference it from a .NET console project.

Keys this example writes (case-sensitive):

  • Work item: General.Source = api-import.
  • Document: Index.Vendor, Index.InvoiceNumber. Use the field keys of your content type.
  • Optional document key General.DocTypeId: the content type's internal id. Upload To Destination reads it to choose the destination. Set it only if your workflow does not classify the document. Get the id from V1_RepositoryAPI/GetContentTypes (Data[].InternalId; needs Access Repository).

The program

CreateWorkItem.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using KL.APIClient.Api;
using KL.APIClient.Client;
using KL.APIClient.Model;
using Newtonsoft.Json;

public static class CreateWorkItem
{
    public static async Task Main(string[] args)
    {
        string filePath = args[0];                 // for example C:\invoices\Invoice_20481.pdf
        string workflowName = "Invoice Approval";  // the workflow to start

        var config = new Configuration { BasePath = Environment.GetEnvironmentVariable("KnowledgeLakeApiURL") };
        config.AddApiKey("TempIdentityToken", Environment.GetEnvironmentVariable("KnowledgeLakeApiToken"));
        var workItems = new V1KWorkItemAPIApi(config);
        var workflows = new V1WorkflowAPIApi(config);

        // 1. Find the workflow id by name.
        var all = await workflows.V1WorkflowAPIControllerGetAllWorkflowsAsync();
        if (!all.Success) throw new Exception("GetAllWorkflows failed: " + all.MessageKey);
        var workflow = all.Data.FirstOrDefault(w => w.WorkflowName == workflowName);
        if (workflow == null) throw new Exception("No active workflow named " + workflowName);

        // 2. Create the work item.
        var created = await workItems.V1KWorkItemAPIControllerNewWorkItemAsync(new WorkItemCreationRequestParameter
        {
            WorkItemName = Path.GetFileNameWithoutExtension(filePath),
            Metadata = new List<MetadataValueDTO>
            {
                new MetadataValueDTO { Bucket = "General", Key = "Source", Value = "api-import" }
            }
        });
        if (!created.Success) throw new Exception("NewWorkItem failed: " + created.MessageKey);
        Guid workItemId = created.Data.WorkItemId;
        Console.WriteLine("Created work item " + workItemId);   // record it before the next call

        // 3. Add the file as a document. MetadataParameter is a JSON string.
        string documentMetadata = JsonConvert.SerializeObject(new AddPaasDocumentMetadataParameter
        {
            Metadata = new List<MetadataValueDTO>
            {
                new MetadataValueDTO { Bucket = "Index", Key = "Vendor", Value = "Gateway Fleet Services LLC" },
                new MetadataValueDTO { Bucket = "Index", Key = "InvoiceNumber", Value = "20481" }
            }
        });

        Guid documentId;
        using (var stream = File.OpenRead(filePath))
        {
            var added = await workItems.V1KWorkItemAPIControllerAddDocumentAsync(
                workItemId, stream, Path.GetFileName(filePath), "application/pdf", documentMetadata);
            if (!added.Success) throw new Exception("AddDocument failed: " + added.MessageKey);
            documentId = added.Data.DocumentId;
        }

        // 4. Start the workflow (latest version, first step).
        var sent = await workflows.V1WorkflowAPIControllerSendToWorkflowAsync(new RunWorkflowParameter
        {
            WorkflowId = workflow.WorkflowId,
            WorkItemId = workItemId
        });
        if (!sent.Success) throw new Exception("SendToWorkflow failed: " + sent.MessageKey);

        Console.WriteLine("Work item " + workItemId + ", document " + documentId + ", sent to " + workflowName);
    }
}

How it works

  • GetAllWorkflows returns only active workflows the token's user can view, so a missing name means a permission or status problem, not a typo alone.
  • NewWorkItem creates an empty work item outside any workflow. It is not idempotent: the program prints the id at once so a failed later call can reuse it instead of creating a second work item.
  • AddDocument is multipart/form-data. The document metadata travels as a JSON string in MetadataParameter, not as a nested object.
  • SendToWorkflow comes last. The workflow starts working the item at once, so every document must already be there.
  • Any call that returns HTTP 400 or higher throws ApiException; ErrorContent holds Messages[].MessageKey. See Creating a C# client.

Test it

  1. Run the program with a small PDF: dotnet run -- C:\invoices\Invoice_20481.pdf.
  2. Open Monitor and find the work item by its name (the file name without extension).
  3. Open the document in the Index app, or call V1_KWorkItemAPI/GetWorkItem, and check Index.Vendor and Index.InvoiceNumber.

You should see

the work item in the Invoice Approval workflow, at its first step, with one document whose Vendor is Gateway Fleet Services LLC and whose InvoiceNumber is 20481.

What can go wrong

What you see Cause and fix
HTTP 401 on GetAllWorkflows or SendToWorkflow The token does not have Manage Workflows.
No active workflow with that name Check the name, that the workflow is active, and the user's workflow permissions.
User does not run have permission to workflow. Give the service account Run permission on the workflow.
File extension not allowed: .xyz The tenant does not accept that file type.
HTTP 413 on AddDocument A component in front of your tenant refused the request size. Ask Support for the limit that applies to your tenant.
The workflow runs before all files are in You called SendToWorkflow too early. Add every document first.
Upload To Destination fails with Document with id '...' has no assigned content type. The document has no General.DocTypeId. Set it when you add the document, or classify in the workflow.
A retry created a second work item Reuse the recorded WorkItemId instead of calling NewWorkItem again.

Variations

  • Several files in one work item Call AddDocument once per file, then SendToWorkflow once.
  • Start at a later step Pass WorkflowVersion and WorkflowStep to SendToWorkflow.
  • Other languages The same three calls in Python, PowerShell, Node.js and cURL.