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
TitleandUploadFileName(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¶
- Give the service account the Manage Work Items API feature and create a token with it. See Authentication.
- Set
KnowledgeLakeApiURL(for examplehttps://yourcompany.knowledgelake.io/api) andKnowledgeLakeApiTokenin the environment. - Generate KL.APIClient from your tenant's spec and reference it from a .NET console project.
- Get a work item id. It is in Monitor, in the
WorkItemIdheader that Call External API sends to your endpoint, or in the results ofV1_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¶
GetWorkItemreads 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 valueDocumentId. Readwalks bucket, then key, and returns""for anything missing. IndexingMetadata["Index"]["Title"]directly throws when one document lacks the key.- Each document can have several files. The program picks the
Inputfile (what came in) and falls back to itsFileNamewhenUploadFileNameis empty. GetDocumentFilereturns bytes, not an envelope. The generated client returns a stream; on failure it throwsApiExceptionwith the 412 envelope.
Test it¶
- Run the program with the id of a work item that has two or three documents:
dotnet run -- <work item id>. - Compare the JSON with the work item in Monitor or the Index app.
- 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. |