Node.js API Examples¶
These examples call the KnowledgeLake API from Node.js with the built-in fetch, FormData and Blob. They need no packages. Save the helper once, then use the task you need.
At a glance
- Tool Node.js 18 or later, no packages
- Tasks on this page Test a token, get a work item, upsert metadata, run a saved search, create a work item and send it to a workflow, list failed jobs
- Token features used Manage Work Items, Manage Workflows, Run Searches, Query Jobs
- Pattern One helper does every JSON call, checks
Success, and fails withMessageKeyorMessages[].MessageKey
For the call shape, the token header and the response envelope, see the Introduction. For every work item action, see the KWorkItem API reference.
These samples run in Node.js on your machine or server. They do not run inside a Custom Step or a Custom Behavior, which have no fetch and no require.
Setup¶
- Node.js 18 or later.
- Environment variables
KL_BASE_URL(for examplehttps://yourcompany.knowledgelake.io/api) andKL_API_TOKEN. Never write the token into the script.
Save this as kl.js. The other samples use it.
const BASE = process.env.KL_BASE_URL.replace(/\/$/, "");
const TOKEN = process.env.KL_API_TOKEN;
// Return Data from the envelope, or throw with the API's message text.
async function data(action, response) {
const text = await response.text();
let env;
try {
env = JSON.parse(text);
} catch (e) {
throw new Error(action + ": HTTP " + response.status + " " + text.slice(0, 300));
}
if (response.status === 200 && env.Success) {
return env.Data;
}
const messages = (env.Messages || []).map(function (m) { return m.MessageKey; });
throw new Error(action + ": HTTP " + response.status + " " + (messages.join("; ") || env.MessageKey));
}
// POST one action with a JSON body.
async function kl(action, body) {
const response = await fetch(BASE + "/" + action, {
method: "POST",
headers: { "TempIdentityToken": TOKEN, "Content-Type": "application/json" },
body: JSON.stringify(body || {})
});
return data(action, response);
}
module.exports = { BASE, TOKEN, data, kl };
The error text is in MessageKey (or Messages[].MessageKey). There is no Message property.
Get a work item and upsert metadata¶
const { kl } = require("./kl");
async function main() {
const workItemId = process.argv[2];
const wi = await kl("V1_KWorkItemAPI/GetWorkItem", { WorkItemId: workItemId });
for (const doc of wi.Documents) {
const index = doc.Metadata.Index || {};
process.stdout.write(doc.Id + " " + (index.Title || "") + "\n");
}
// Work item level (routes read these values)
await kl("V1_KWorkItemAPI/UpsertWorkItemMetadata", {
WorkItemId: workItemId,
Metadata: [{ Bucket: "Index", Key: "NeedsReview", Value: "Yes" }]
});
// One document
await kl("V1_KWorkItemAPI/UpsertDocumentMetadata", {
WorkItemId: workItemId,
DocumentId: wi.Documents[0].Id,
Metadata: [
{ Bucket: "Index", Key: "ApprovalStatus", Value: "Approved" },
{ Bucket: "General", Key: "EditedBy", Value: "node" }
]
});
}
main().catch(function (e) { console.error(e.message); process.exit(1); });
A document's id is Id. Every value is a string: send "true" and "1250.00", not true and 1250.
Run a saved search¶
const { kl } = require("./kl");
async function main() {
const searches = await kl("V1_RepositoryAPI/GetSavedSearches", {});
const search = searches.find(function (s) { return s.SavedSearchName === "Invoices by Vendor"; });
const cond = search.SearchConditions.find(function (c) { return c.ParameterInternalName === "VendorName"; });
const pageSize = 200;
for (let start = 0; ; start += pageSize) {
const strings = {};
strings[cond.ConditionId] = "Gateway Fleet Services LLC";
const page = await kl("V1_RepositoryAPI/RunSavedSearch", {
SearchId: search.SavedSearchId,
SearchCatalogId: search.SearchCatalogId,
StartRow: start,
RowLimit: pageSize,
SearchConditions: { Strings: strings }
});
for (const item of page.Results) {
process.stdout.write(item.ResultItemId + " " + item.Data.map(function (d) { return d.InternalPropertyId + "=" + d.Value; }).join(" | ") + "\n");
}
if (page.Results.length < pageSize) break;
}
}
main().catch(function (e) { console.error(e.message); process.exit(1); });
Create a work item and send it to a workflow¶
const fs = require("fs");
const path = require("path");
const { BASE, TOKEN, data, kl } = require("./kl");
async function main() {
const filePath = process.argv[2];
const workflowName = "Invoice Approval";
// 1. Create the work item.
const created = await kl("V1_KWorkItemAPI/NewWorkItem", {
WorkItemName: path.parse(filePath).name,
Metadata: [{ Bucket: "General", Key: "Source", Value: "node" }]
});
// 2. Add the file (multipart/form-data). MetadataParameter is a JSON string.
const form = new FormData();
form.append("WorkItemId", created.WorkItemId);
form.append("File", new Blob([fs.readFileSync(filePath)], { type: "application/pdf" }), path.basename(filePath));
form.append("MetadataParameter", JSON.stringify({
Metadata: [{ Bucket: "Index", Key: "InvoiceNumber", Value: "20481" }]
}));
const response = await fetch(BASE + "/V1_KWorkItemAPI/AddDocument", {
method: "POST",
headers: { "TempIdentityToken": TOKEN }, // fetch sets the multipart Content-Type
body: form
});
const added = await data("AddDocument", response);
// 3. Start the workflow.
const workflows = await kl("V1_WorkflowAPI/GetAllWorkflows", {});
const workflow = workflows.find(function (w) { return w.WorkflowName === workflowName; });
await kl("V1_WorkflowAPI/SendToWorkflow", { WorkflowId: workflow.WorkflowId, WorkItemId: created.WorkItemId });
process.stdout.write("Created " + created.WorkItemId + ", document " + added.DocumentId + "\n");
}
main().catch(function (e) { console.error(e.message); process.exit(1); });
Do not set Content-Type on the upload yourself; fetch adds the multipart boundary. Add every document before SendToWorkflow. See Create a work item and send it to a workflow.
List failed jobs¶
const { kl } = require("./kl");
async function main() {
const jobs = await kl("V1_JobsAPI/QueryForJobRuns", { JobStatus: "Error", PageSize: 200 });
for (const job of jobs) {
process.stdout.write(job.JobDisplayName + " " + job.JobID + " " + job.LastRuntime + "\n");
}
// Rerun one after you checked it (needs Manage Jobs):
// await kl("V1_JobsAPI/ResubmitJob", { JobInstanceID: "<JobID>" });
}
main().catch(function (e) { console.error(e.message); process.exit(1); });
For a full watchdog with history, RPA tasks and safe retries, see Find and resubmit failed jobs.
What can go wrong¶
| What you see | Cause and fix |
|---|---|
fetch is not defined |
Node.js is older than 18. |
| The upload fails with a JSON parse error | You set Content-Type yourself on the multipart request. Let fetch set it. |
Cannot read properties of undefined (reading 'Title') |
The document has no Index bucket. Guard with doc.Metadata.Index || {}. |
| These samples do not run in a Custom Step or a behavior | Those engines have no fetch and no require. |