Skip to content

Read a Work Item and Download Its Files

A county records office wants to export each work item to its records system: the document id, file name and title of every document, plus the original files. The work item is still in a workflow, so the export must not lock it or change it.

At a glance

  • Extension point REST API from your own code
  • You need A token with Manage Work Items; content type fields Title and UploadFileName (or your own keys)
  • Teaches Read a work item without locking it, read metadata that may be missing, pick the right file and download it

Set it up

  1. Give the service account the Manage Work Items API feature and create a token with it. See Authentication.
  2. Set KnowledgeLakeApiURL (for example https://yourcompany.knowledgelake.io/api) and KnowledgeLakeApiToken in the environment.
  3. Generate KL.APIClient from your tenant's spec and reference it from a .NET console project.
  4. Get a work item id. It is in Monitor, in the WorkItemId header that Call External API sends to your endpoint, or in the results of V1_KWorkItemAPI/QueryWorkState.

Keys this example reads (case-sensitive): Index.Title and Index.UploadFileName on each document. A key that a document does not have is missing from its Metadata dictionary, so the program reads with a helper that returns a default.

The program

WorkItemReport.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 WorkItemReport
{
    public class DocumentRow
    {
        public Guid DocumentId { get; set; }
        public string FileName { get; set; }
        public string Title { get; set; }
    }

    public static async Task Main(string[] args)
    {
        Guid workItemId = Guid.Parse(args[0]);
        string downloadFolder = args.Length > 1 ? args[1] : null;

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

        var response = await workItems.V1KWorkItemAPIControllerGetWorkItemAsync(new PaasWorkItemIdDTO { WorkItemId = workItemId });
        if (!response.Success) throw new Exception("GetWorkItem failed: " + response.MessageKey);

        var rows = new List<DocumentRow>();
        foreach (var document in response.Data.Documents)
        {
            var input = document.Files.FirstOrDefault(f => f.Type == DocumentFileType.Input);
            string fileName = Read(document.Metadata, "Index", "UploadFileName");
            if (fileName == "" && input != null) fileName = input.FileName;

            rows.Add(new DocumentRow
            {
                DocumentId = document.Id,
                FileName = fileName,
                Title = Read(document.Metadata, "Index", "Title")
            });

            // Optional: download the input file of each document.
            if (downloadFolder != null && input != null)
            {
                using (var file = await workItems.V1KWorkItemAPIControllerGetDocumentFileAsync(new GetDocumentFileParameter
                {
                    WorkItemId = workItemId,
                    DocumentId = document.Id,
                    DocumentFileId = input.Id
                }))
                using (var output = File.Create(Path.Combine(downloadFolder, document.Id + "_" + input.FileName)))
                {
                    await file.CopyToAsync(output);
                }
            }
        }

        Console.WriteLine(JsonConvert.SerializeObject(new { WorkItemId = workItemId, Name = response.Data.Name, Documents = rows }, Formatting.Indented));
    }

    // Metadata is bucket -> key -> value. Every value is a string. Missing keys return "".
    private static string Read(Dictionary<string, Dictionary<string, string>> metadata, string bucket, string key)
    {
        if (metadata != null && metadata.TryGetValue(bucket, out var values) && values.TryGetValue(key, out var value))
        {
            return value ?? "";
        }
        return "";
    }
}

How it works

  • GetWorkItem reads the whole work item in one call and takes no lock, so the export can run while the item waits in a task or runs in a step.
  • The API names a document's id Id. A Custom Step names the same value DocumentId.
  • Read walks bucket, then key, and returns "" for anything missing. Indexing Metadata["Index"]["Title"] directly throws when one document lacks the key.
  • Each document can have several files. The program picks the Input file (what came in) and falls back to its FileName when UploadFileName is empty.
  • GetDocumentFile returns bytes, not an envelope. The generated client returns a stream; on failure it throws ApiException with the 412 envelope.

Test it

  1. Run the program with the id of a work item that has two or three documents: dotnet run -- <work item id>.
  2. Compare the JSON with the work item in Monitor or the Index app.
  3. Run it again with a folder as the second argument, and open the downloaded files.

You should see

one JSON row per document with its id, file name and title, and, with a folder, one file per document named {DocumentId}_{FileName}. The work item stays where it was in its workflow.

What can go wrong

What you see Cause and fix
HTTP 412 saying the work item does not exist The id is wrong, or the work item was deleted after its workflow finished and its retention ran out.
KeyNotFoundException Some code reads Metadata["Index"]["Title"] directly. Use a helper like Read.
A document has no Input file Check Type before you download. Fall back to the Output file if you need what the workflow produced.
Values look stale A workflow step can change the work item between your read and your use. Read again just before you act on a value.
Python or PowerShell users The same read is on the Python and PowerShell pages.