Python API Examples¶
These examples call the KnowledgeLake API from Python with the requests library. Copy the helper once, then use the task you need.
At a glance
- Tool Python 3.9 or later with
requests - 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.
Setup¶
Set KL_BASE_URL (for example https://yourcompany.knowledgelake.io/api) and KL_API_TOKEN in the environment. Never write the token into the script.
import json
import os
import requests
BASE = os.environ["KL_BASE_URL"].rstrip("/")
TOKEN = os.environ["KL_API_TOKEN"]
class KLError(Exception):
pass
def _data(action, r):
"""Return Data from the envelope, or raise with the API's message text."""
try:
env = r.json()
except ValueError:
raise KLError(f"{action}: HTTP {r.status_code} {r.text[:300]}")
if r.status_code == 200 and env.get("Success"):
return env.get("Data")
messages = [m.get("MessageKey", "") for m in env.get("Messages", [])] or [env.get("MessageKey", "")]
raise KLError(f"{action}: HTTP {r.status_code} {'; '.join(messages)}")
def kl(action, body=None):
"""POST one action with a JSON body."""
r = requests.post(f"{BASE}/{action}", json=body or {}, timeout=120,
headers={"TempIdentityToken": TOKEN})
return _data(action, r)
requests sets Content-Type: application/json when you pass json=. The error text is in MessageKey (or Messages[].MessageKey). There is no Message property.
Test the token¶
HTTP 401 means the token is wrong or lacks Manage Workflows.
Get a work item¶
work_item_id = "<work item guid>"
wi = kl("V1_KWorkItemAPI/GetWorkItem", {"WorkItemId": work_item_id})
print(wi["Name"])
for doc in wi["Documents"]:
title = doc["Metadata"].get("Index", {}).get("Title", "")
print(doc["Id"], title)
A document's id is Id. A key that a document does not have is missing from its dictionary, so use .get.
Upsert metadata¶
# Work item level (routes read these values)
kl("V1_KWorkItemAPI/UpsertWorkItemMetadata", {
"WorkItemId": work_item_id,
"Metadata": [{"Bucket": "Index", "Key": "NeedsReview", "Value": "Yes"}],
})
# One document
kl("V1_KWorkItemAPI/UpsertDocumentMetadata", {
"WorkItemId": work_item_id,
"DocumentId": wi["Documents"][0]["Id"],
"Metadata": [
{"Bucket": "Index", "Key": "ApprovalStatus", "Value": "Approved"},
{"Bucket": "General", "Key": "EditedBy", "Value": "python"},
],
})
Every value is a string: send "true" and "1250.00", not True and 1250.
Run a saved search¶
searches = kl("V1_RepositoryAPI/GetSavedSearches", {})
search = next(s for s in searches if s["SavedSearchName"] == "Invoices by Vendor")
cond = next(c for c in search["SearchConditions"] if c["ParameterInternalName"] == "VendorName")
start, page_size = 0, 200
while True:
page = kl("V1_RepositoryAPI/RunSavedSearch", {
"SearchId": search["SavedSearchId"],
"SearchCatalogId": search["SearchCatalogId"],
"StartRow": start,
"RowLimit": page_size,
"SearchConditions": {"Strings": {cond["ConditionId"]: "Gateway Fleet Services LLC"}},
})
for item in page["Results"]:
print(item["ResultItemId"], {d["InternalPropertyId"]: d["Value"] for d in item["Data"]})
if len(page["Results"]) < page_size:
break
start += page_size
See Run a saved search.
Create a work item and send it to a workflow¶
file_path = "invoices/Invoice_20481.pdf"
workflow_name = "Invoice Approval"
# 1. Create the work item.
new = kl("V1_KWorkItemAPI/NewWorkItem", {
"WorkItemName": os.path.splitext(os.path.basename(file_path))[0],
"Metadata": [{"Bucket": "General", "Key": "Source", "Value": "python"}],
})
new_id = new["WorkItemId"]
# 2. Add the file (multipart/form-data). MetadataParameter is a JSON string.
doc_metadata = json.dumps({"Metadata": [{"Bucket": "Index", "Key": "InvoiceNumber", "Value": "20481"}]})
with open(file_path, "rb") as f:
r = requests.post(f"{BASE}/V1_KWorkItemAPI/AddDocument", timeout=600,
headers={"TempIdentityToken": TOKEN},
data={"WorkItemId": new_id, "MetadataParameter": doc_metadata},
files={"File": (os.path.basename(file_path), f, "application/pdf")})
added = _data("AddDocument", r)
# 3. Start the workflow.
workflow = next(w for w in kl("V1_WorkflowAPI/GetAllWorkflows") if w["WorkflowName"] == workflow_name)
kl("V1_WorkflowAPI/SendToWorkflow", {"WorkflowId": workflow["WorkflowId"], "WorkItemId": new_id})
print("Created", new_id, "document", added["DocumentId"])
Do not set Content-Type yourself on the upload. requests sets the multipart boundary. Add every document before SendToWorkflow. See Create a work item and send it to a workflow.
Wait for the workflow (optional)¶
import time
while True:
state = kl("V1_KWorkItemAPI/GetWorkState", {"WorkItemId": new_id})
if state["WorkStatus"] in ("Completed", "Error", "Hold", "Stopped", 0, 1, 4, 5):
print(state["WorkStatus"])
break
time.sleep(2) # never poll faster than every 1.5 seconds
WorkStatus is documented by name. The check above also accepts the numbers in case your tenant returns them (see the reference).
List failed jobs¶
for job in kl("V1_JobsAPI/QueryForJobRuns", {"JobStatus": "Error", "PageSize": 200}):
print(job["JobDisplayName"], job["JobID"], job["LastRuntime"])
# Rerun one after you checked it (needs Manage Jobs):
# kl("V1_JobsAPI/ResubmitJob", {"JobInstanceID": "<JobID>"})
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 |
|---|---|
KeyError on a metadata key |
The document does not have it. Use .get at each level. |
| HTTP 422 | A property name has the wrong case, or an id is not a GUID. |
The upload fails with HTTP 412 File extension not allowed |
The tenant does not accept that file type. |
requests raises a timeout on a large upload |
Raise timeout on the upload call. |