Your Own Endpoint: Azure Functions and AWS Lambda¶
When workflow logic needs another system, the document file, unit tests or source control, write it as your own HTTPS endpoint and call it from the workflow with Call External API. The endpoint:
- receives the work item id in a header;
- reads what it needs through the KnowledgeLake API;
- writes its results back;
- returns a status code that the workflow can route on.
Choose this over a Custom Step when the logic must reach the network, read file bytes, run longer than two minutes, or be tested and versioned like other code.
At a glance
- Runs On your platform (Azure Functions, AWS Lambda, any HTTPS host), when a Call External API step calls it.
- Language any. This page uses C# with the generated
KL.APIClient. Other languages send plain HTTPS. - Authored in Your own project and source control. The workflow holds only the Call External API step.
- Can reach Anything your platform allows, plus the KnowledgeLake API at
https://{tenant}/apiwith a token. - Best for Enrichment from other systems, file processing, logic you must unit test.
The older Send To Azure Function step is legacy. Use Call External API for new work.
The round trip¶
sequenceDiagram
participant W as Workflow
participant F as Your endpoint
participant K as KnowledgeLake API
W->>F: POST from Call External API with header WorkItemId
F->>F: Check the function key, read WorkItemId
F->>K: V1_KWorkItemAPI/GetWorkItem with the token
K-->>F: Work item, documents and metadata
opt The logic needs the file
F->>K: V1_KWorkItemAPI/GetDocumentFile
K-->>F: File bytes
end
F->>K: UpsertDocumentMetadata and UpsertWorkItemMetadata
K-->>F: Success true
F-->>W: 2xx with a small JSON body, or 4xx or 5xx on failure
W->>W: Write ApiResults, then evaluate routes
- The workflow reaches the Call External API step. The step sends your request and adds the header
WorkItemId. - Your endpoint authenticates the call with its platform's own method: the
?code=function key on Azure, an API key or IAM on AWS. - The endpoint reads
WorkItemIdfrom the header. If it is missing, it fails at once. - The endpoint calls the KnowledgeLake API:
V1_KWorkItemAPI/GetWorkItem, optionallyV1_KWorkItemAPI/GetDocumentFile, thenV1_KWorkItemAPI/UpsertDocumentMetadataorV1_KWorkItemAPI/UpsertWorkItemMetadata. - The endpoint returns 2xx only when the work is done. On any failure it returns 4xx or 5xx, so the step fails instead of reporting success with nothing done.
- The step writes
ApiResults.LastHttpStatusCodeand, if set, the response body under the Response Metadata Key. The routes run.
Runtime contract¶
| Item | Value |
|---|---|
| Engine | Your platform: Azure Functions, AWS Lambda, or any HTTPS host. |
| Runs when | The Call External API step runs. |
| Timeout | The lower of the step's Timeout and your platform's limit. |
| Network access | Anything your platform allows. The KnowledgeLake API is https://{tenant}/api. |
| Input | The WorkItemId header and your request body. Everything else comes from the API. |
| Output | Writes through the API, and a status code plus a small body that the step stores in ApiResults. |
Rules¶
- Read
WorkItemIdfrom the header, not from the body. - Keep the API URL and token in configuration: Azure app settings, Lambda environment variables, or a key vault. Never put a token in code or in a committed file.
- Use a token created for a service account. A token acts as the user who created it. It needs the API feature Manage Work Items for the
V1_KWorkItemAPIactions. See Authentication. - Check
Successon every API response. TreatSuccess: falseas a failure, even on HTTP 200. - Return non-2xx on failure. A caught exception followed by HTTP 200 is a silent no-op in the workflow.
- Make writes idempotent. The step can run again after a timeout or a retry. Upsert a final value; never append to it or add to a count.
- Bucket and key names are exact, case-sensitive strings.
Indexholds indexed fields.Generalholds other values. Do not write toSystem. - Return within the step timeout and the platform limit. If the work takes longer, accept the request, finish the work, and write a result key that a later step checks.
The function¶
This Azure Function (in-process model, .NET 8) reads each document's Index.InvoiceTotal and compares it with a limit from app settings. It writes the decision back:
- Documents
Index.NeedsReview(YesorNo) andGeneral.ReviewReason - Work item
General.HighValueCountandGeneral.ReviewLimit
To build it:
- Copy the files below into a new project folder.
- Generate
KL.APIClientfrom your tenant's spec into aKLClientfolder next to the project folder (not inside it, or the function project compiles the client's files twice). See Generate the client.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using KL.APIClient.Client;
using KL.APIClient.Model;
namespace KLFunctionExample
{
// Called from a workflow by a Call External API step (POST).
// Per document: Index.NeedsReview = "Yes" | "No", General.ReviewReason = why.
// Per work item: General.HighValueCount, General.ReviewLimit.
// Any failure returns 400, so the workflow step fails instead of silently succeeding.
public static class FlagHighValueInvoicesFunction
{
private const decimal DefaultLimit = 10000m;
[FunctionName("FlagHighValueInvoices")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
ILogger log)
{
try
{
// 1. Which work item? Call External API sends it in a header.
Guid workItemId = Guid.Empty;
if (req.Headers.ContainsKey("WorkItemId"))
{
workItemId = Guid.Parse(req.Headers["WorkItemId"]);
}
#if DEBUG
// Local runs only: a Debug build may use a test id when the header is missing.
if (workItemId == Guid.Empty)
{
string localId = Environment.GetEnvironmentVariable("LocalTestWorkItemId");
if (!string.IsNullOrEmpty(localId))
{
workItemId = Guid.Parse(localId);
}
}
#endif
if (workItemId == Guid.Empty)
{
throw new Exception("Missing WorkItemId header");
}
// 2. Configuration from app settings, never from code.
string token = Environment.GetEnvironmentVariable("KnowledgeLakeApiToken");
string apiUrl = Environment.GetEnvironmentVariable("KnowledgeLakeApiURL");
if (string.IsNullOrEmpty(token) || string.IsNullOrEmpty(apiUrl))
{
throw new Exception("KnowledgeLakeApiToken or KnowledgeLakeApiURL is not set");
}
decimal limit = ReadLimit(Environment.GetEnvironmentVariable("ReviewLimit"));
// 3. The generated client.
var config = new Configuration { BasePath = apiUrl };
config.AddApiKey("TempIdentityToken", token);
var client = new KL.APIClient.Api.V1KWorkItemAPIApi(config);
// 4. Read the work item.
var workItem = await client.V1KWorkItemAPIControllerGetWorkItemAsync(
new PaasWorkItemIdDTO { WorkItemId = workItemId });
if (!workItem.Success)
{
throw new Exception("GetWorkItem failed");
}
// 5. Decide per document and upsert the decision.
int flagged = 0;
foreach (var document in workItem.Data.Documents)
{
string rawTotal = GetMetadataValue(document.Metadata, "Index", "InvoiceTotal");
var decision = Evaluate(document.Id, rawTotal, limit);
if (decision.NeedsReview) flagged++;
var update = await client.V1KWorkItemAPIControllerUpsertDocumentMetadataAsync(
new UpsertPaasDocumentMetadataParameter
{
WorkItemId = workItemId,
DocumentId = document.Id,
Metadata = new List<MetadataValueDTO>
{
new MetadataValueDTO { Bucket = "Index", Key = "NeedsReview", Value = decision.NeedsReview ? "Yes" : "No" },
new MetadataValueDTO { Bucket = "General", Key = "ReviewReason", Value = decision.Reason }
}
});
if (!update.Success)
{
throw new Exception("UpsertDocumentMetadata failed for " + document.Id);
}
}
// 6. Work-item values that a route can read.
var summary = await client.V1KWorkItemAPIControllerUpsertWorkItemMetadataAsync(
new UpsertPaasWorkItemMetadataParameter
{
WorkItemId = workItemId,
Metadata = new List<MetadataValueDTO>
{
new MetadataValueDTO { Bucket = "General", Key = "HighValueCount", Value = flagged.ToString(CultureInfo.InvariantCulture) },
new MetadataValueDTO { Bucket = "General", Key = "ReviewLimit", Value = limit.ToString("0.##", CultureInfo.InvariantCulture) }
}
});
if (!summary.Success)
{
throw new Exception("UpsertWorkItemMetadata failed");
}
// This body lands in ApiResults.<Response Metadata Key>.
return new OkObjectResult(new { flagged, documents = workItem.Data.Documents.Count, limit });
}
catch (Exception ex)
{
log.LogError(ex, "FlagHighValueInvoices failed");
return new BadRequestObjectResult("Error: " + ex.Message); // the workflow step fails
}
}
// ---- Pure logic: no API calls, so it is unit-testable without a tenant. ----
internal sealed class DocumentDecision
{
public Guid DocumentId { get; set; }
public decimal? Total { get; set; }
public bool NeedsReview { get; set; }
public string Reason { get; set; }
}
// Over the limit needs review. A missing or unreadable total also needs review.
internal static DocumentDecision Evaluate(Guid documentId, string rawTotal, decimal limit)
{
var decision = new DocumentDecision { DocumentId = documentId };
if (!TryParseAmount(rawTotal, out decimal total))
{
decision.NeedsReview = true;
decision.Reason = string.IsNullOrWhiteSpace(rawTotal)
? "No InvoiceTotal on the document"
: string.Format(CultureInfo.InvariantCulture, "InvoiceTotal '{0}' could not be read as a number", rawTotal);
return decision;
}
decision.Total = total;
decision.NeedsReview = total > limit;
decision.Reason = string.Format(CultureInfo.InvariantCulture,
decision.NeedsReview ? "Total {0:N2} is over the {1:N2} limit" : "Total {0:N2} is within the {1:N2} limit",
total, limit);
return decision;
}
// Accepts "12,500.00", "$12500" and " 12 500.00 ". A comma is a thousands separator.
internal static bool TryParseAmount(string raw, out decimal amount)
{
amount = 0m;
if (string.IsNullOrWhiteSpace(raw))
{
return false;
}
string cleaned = new string(raw.Where(c => char.IsDigit(c) || c == '.' || c == '-').ToArray());
return cleaned.Length > 0 && decimal.TryParse(cleaned,
NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign,
CultureInfo.InvariantCulture, out amount);
}
// The app setting, or the default when it is unset or unreadable.
internal static decimal ReadLimit(string setting)
{
return TryParseAmount(setting, out decimal limit) && limit > 0 ? limit : DefaultLimit;
}
// Metadata[bucket][key], or null when either level is missing.
internal static string GetMetadataValue(Dictionary<string, Dictionary<string, string>> metadata, string bucket, string key)
{
if (metadata == null || !metadata.TryGetValue(bucket, out var values) || values == null)
{
return null;
}
return values.TryGetValue(key, out var value) ? value : null;
}
}
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<AzureFunctionsVersion>v4</AzureFunctionsVersion>
</PropertyGroup>
<ItemGroup>
<!-- Lets the test project call the internal pure methods. -->
<InternalsVisibleTo Include="KLFunctionApp.Tests" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="4.4.1" />
</ItemGroup>
<ItemGroup>
<!-- The KnowledgeLake client you generated from your tenant's spec. -->
<ProjectReference Include="..\KLClient\src\KL.APIClient\KL.APIClient.csproj" />
</ItemGroup>
<ItemGroup>
<None Update="host.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="local.settings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>Never</CopyToPublishDirectory>
</None>
</ItemGroup>
</Project>
Add a host.json with { "version": "2.0" } next to it, or keep the one func init creates.
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet",
"FUNCTIONS_INPROC_NET8_ENABLED": "1",
"KnowledgeLakeApiURL": "https://your-tenant.example.com/api",
"ReviewLimit": "10000",
"LocalTestWorkItemId": ""
}
}
Copy it to local.settings.json and keep that file out of source control. The token is not in this file: set it in your user environment variable KnowledgeLakeApiToken, and in the Azure app settings when you deploy.
using System;
using KLFunctionExample;
using Xunit;
namespace KLFunctionApp.Tests
{
public class FlagHighValueInvoicesTests
{
[Theory]
[InlineData("12,500.00", 12500)]
[InlineData("$9,999.99", 9999.99)]
[InlineData(" 10 000.50 ", 10000.50)]
public void TryParseAmount_ReadsIndexPanelFormats(string raw, decimal expected)
{
Assert.True(FlagHighValueInvoicesFunction.TryParseAmount(raw, out decimal amount));
Assert.Equal(expected, amount);
}
[Fact]
public void Evaluate_OverLimit_NeedsReview()
{
var decision = FlagHighValueInvoicesFunction.Evaluate(Guid.NewGuid(), "12,500.00", 10000m);
Assert.True(decision.NeedsReview);
}
[Fact]
public void Evaluate_ExactlyAtLimit_DoesNotNeedReview()
{
var decision = FlagHighValueInvoicesFunction.Evaluate(Guid.NewGuid(), "10000", 10000m);
Assert.False(decision.NeedsReview);
}
[Fact]
public void Evaluate_MissingTotal_NeedsReview()
{
var decision = FlagHighValueInvoicesFunction.Evaluate(Guid.NewGuid(), null, 10000m);
Assert.True(decision.NeedsReview);
Assert.Equal("No InvoiceTotal on the document", decision.Reason);
}
}
}
The test project is a standard xUnit project (dotnet new xunit) on .NET 8 with a project reference to KLFunctionApp.csproj. Run dotnet test. The tests need no tenant.
Keep decision logic in pure methods like Evaluate, and unit test them. Keep the API calls in Run.
Wire it to the workflow¶
- Deploy the function app. Add the app settings
KnowledgeLakeApiURL(https://{tenant}/api),KnowledgeLakeApiToken,ReviewLimit, andFUNCTIONS_INPROC_NET8_ENABLED=1. - In the workflow, add Call External API:
- External API URL:
https://{function-app}.azurewebsites.net/api/FlagHighValueInvoices?code={function key} - REST Verb:
POST - Response Metadata Key:
FlagResult - Timeout:
120(below the platform limit) - Route on
General.HighValueCount, or onApiResults.LastHttpStatusCodeif the step's Error Behavior is Continue. See Routes.
You are done when
a test work item shows ApiResults.LastHttpStatusCode = 200, ApiResults.FlagResult = {"flagged":1,"documents":3,"limit":10000} (your numbers), and Index.NeedsReview on each document in Monitor or Insight.
Azure notes¶
- In-process model on .NET 8. Set
FUNCTIONS_INPROC_NET8_ENABLED=1in app settings and inlocal.settings.json. Without it, the first call fails withCould not load file or assembly 'System.Linq, Version=8.0.0.0'. - In-process support ends in November 2026. For a new function app, use the isolated worker model. The round trip, the client and the API calls are the same; only the trigger signature and startup differ.
- Time limits. An HTTP-triggered function must respond within 230 seconds, whatever its function timeout. On the Consumption plan the function timeout is 5 minutes by default and 10 minutes at most.
AWS Lambda notes¶
- Same header, same API calls, same status codes. Read
WorkItemIdfrom the event headers. - Put
KnowledgeLakeApiURLandKnowledgeLakeApiTokenin environment variables or AWS Secrets Manager. - A Lambda function runs for 15 minutes at most. An API Gateway integration ends the request much sooner (about 30 seconds by default). A Lambda function URL waits for the function timeout.
- For languages other than C#, send plain HTTPS: every action is
POST https://{tenant}/api/{Group}/{Action}with a JSON body and the headerTempIdentityToken.
Debug locally¶
The workflow cannot call your machine: Call External API refuses local and private addresses. Debug like this:
- Run a real work item into a test workflow that stops at a hold step (for example a task), so the work item stays open. Copy its id.
- Store the token in your user environment, not in a file you commit.
- Start the function locally (
func start, or F5 in Visual Studio). - Send the request yourself with the header:
Invoke-RestMethod -Method Post -Uri "http://localhost:7071/api/FlagHighValueInvoices" `
-Headers @{ WorkItemId = "<work item id>" }
- Check the metadata in Monitor or Insight.
The function also reads LocalTestWorkItemId from local.settings.json, but only in a Debug build and only when the header is missing, so a real request always wins.
Gotchas¶
Mistakes that bite
- The step succeeds but nothing changed. The function caught an exception and returned 200. Return non-2xx on every failure.
- Values doubled after a retry. The function appended or incremented. Upsert final values.
- HTTP 401 "User Is Unauthorized on endpoint". The token's user lacks a permission, or the token was created without the feature. Create a new token with Manage Work Items.
- HTTP 412 from the API. An application error; the details are in
Messages. After a token change, the usual cause is a feature missing on the new token. - "Api domain is not valid". The URL points at a local or private address. Deploy the function first.
- The step times out, but the function log shows success. The function took longer than the step timeout. Return sooner, or raise the timeout below the platform limit.
Examples¶
- A Function That Reads the Document File: downloads each file with
GetDocumentFileand stores a SHA-256 fingerprint. - Post Form Data to Your API and Handle Failures: a typed JSON body and a failure path with the API's error text.
- Rotate an API Token Without Breaking Workflows: change the function's token with no failed work items.
Copy this into your assistant¶
Paste the block below into your AI assistant together with the AI Assistant Primer, then describe what the endpoint must do. It covers both the Call External API step and your own endpoint. For any API action beyond the four listed, also paste that action's block from your tenant's spec (https://{tenant}/api/OpenAPI/V2_JSON/V2_JSON?domain=https://{tenant}).
# Workflow integration (Call External API + your own endpoint): context for AI assistants
You build an HTTPS endpoint (usually a C# Azure Function) that a KnowledgeLake workflow
calls with the Call External API step, and you configure that step. Use only the facts in this
block. If you need a field, bucket, setting or API action the user has not given, ask for it.
Never invent an API action: if it is not listed here, ask the user to paste its spec block.
## The Call External API step
- Settings: External API URL, REST Verb (only GET and POST work; DELETE, PUT, PATCH fail),
HTTP Headers, Body Type (JSON, XML, Text, Form-Encode; never Raw, which sends no body, and
never Form, which has no multipart boundary), Body, Response Metadata Key, Timeout (seconds,
0 = 15 minutes), plus the step's Retries (0 to 3) and Error Behavior (Stop default, Continue,
Route).
- Any setting can use a preprocessor (gear icon next to the setting's name): Liquid Template
({{ WorkItem.Metadata.Index.Vendor }}), Javascript (last expression is the value; build JSON
bodies with JSON.stringify), or Global Variable.
- The step adds the header WorkItemId. Never put Content-Type in HTTP Headers: the step fails.
- Hosts that resolve to localhost, 127.x, 10.x, 172.16-31.x or 192.168.x, or do not resolve,
are refused with "Api domain is not valid." The endpoint must be public.
- The step cannot send a file. The endpoint downloads files through the API.
- It writes, at work-item level: ApiResults.LastHttpStatusCode (text) and, if the Response
Metadata Key is set, ApiResults.<key> = the response body as text. On non-2xx it writes both,
then the step fails ("HTTP Response status code does not indicate success: ..."). With Error
Behavior Stop the work item errors and routes do not run; with Continue the routes run.
- A timeout or refused host writes nothing, so LastHttpStatusCode can be stale.
## The endpoint contract
1. Read WorkItemId from the request header, never the body. Fail with 400 if it is missing.
2. Authenticate the caller with the platform's method (Azure ?code= function key, AWS API key).
3. Read configuration from environment variables: KnowledgeLakeApiURL (https://{tenant}/api),
KnowledgeLakeApiToken. Never write a token into code, a committed file or a log.
4. Call the KnowledgeLake API. Every action is POST https://{tenant}/api/{Group}/{Action} with a
JSON body and the header TempIdentityToken: <token>. The token acts as the service account
that created it and needs the API feature Manage Work Items for V1_KWorkItemAPI.
5. Check Success on every response. Success false is a failure even on HTTP 200. The API
answers 401 for a bad token or missing feature, 422 for a body that does not match the
schema, and 412 for an application error (details in Messages[].MessageKey).
6. Upsert final values. Never append or increment: the step can run twice (retry, timeout).
7. Return 2xx with a small JSON body only when all work is done; it lands in
ApiResults.<Response Metadata Key>. Return 4xx or 5xx on any failure.
8. Answer inside the step Timeout and the platform limit: Azure HTTP functions must respond
within 230 seconds; API Gateway in front of Lambda ends requests after about 30 seconds.
9. Buckets and keys are exact, case-sensitive strings. Index = indexed fields, General = other
values. Never write System. All values are strings.
## API actions you may use (V1_KWorkItemAPI)
- GetWorkItem { WorkItemId } -> Data: WorkItemId, Name, Metadata[bucket][key], Documents[] with Id,
Metadata, Files[] (Id, FileName, Extension, Type Input|Output|OCR), Pages[]. The API calls a
document's id "Id"; scripts call it DocumentId.
- GetDocumentFile { WorkItemId, DocumentId, DocumentFileId } -> the file bytes (a stream).
- UpsertDocumentMetadata { WorkItemId, DocumentId, Metadata: [{ Bucket, Key, Value }] }
- UpsertWorkItemMetadata { WorkItemId, Metadata: [{ Bucket, Key, Value }] }
## C# client (KL.APIClient, netstandard2.1, generated by the user from their tenant's spec)
```csharp
var config = new Configuration { BasePath = apiUrl }; // KL.APIClient.Client
config.AddApiKey("TempIdentityToken", token);
var client = new KL.APIClient.Api.V1KWorkItemAPIApi(config);
var wi = await client.V1KWorkItemAPIControllerGetWorkItemAsync(new PaasWorkItemIdDTO { WorkItemId = id });
```
Method names: V1KWorkItemAPIController<Action>Async. Models (KL.APIClient.Model):
PaasWorkItemIdDTO, GetDocumentFileParameter, UpsertPaasDocumentMetadataParameter,
UpsertPaasWorkItemMetadataParameter, MetadataValueDTO { Bucket, Key, Value }, DocumentFileType.
The client throws on 401, 412 and 422; let the catch block turn that into a non-2xx response.
## Azure Functions facts
- In-process model on .NET 8 needs FUNCTIONS_INPROC_NET8_ENABLED = 1 in app settings and
local.settings.json, or the first call fails loading System.Linq 8.0.0.0. In-process support
ends in November 2026; suggest the isolated worker model for a new app (same calls).
- [FunctionName], HttpTrigger with AuthorizationLevel.Function and "post".
- Local runs: the workflow cannot reach the developer's machine. Test by sending the request
with a WorkItemId header yourself. A test id may be read from a setting only under #if DEBUG
and only when the header is missing.
## Shape to follow
Header check, configuration, client, GetWorkItem, a loop that calls a pure internal static
Evaluate(...) per document, UpsertDocumentMetadata per document, one UpsertWorkItemMetadata
with a summary a route can read, OkObjectResult(new { ... }) on success, and
BadRequestObjectResult on any exception. Put decision logic in pure methods with xUnit tests.
## Output
Produce: the function file; any new pure methods with xUnit tests; the app settings to add;
the Call External API settings (URL with ?code=, POST, Body Type and body if any, Response
Metadata Key, a Timeout below the platform limit, Error Behavior Continue if a route must
handle failures); the route condition, if one is needed; and a test plan (a work item held at
a task step, the request sent by hand with its WorkItemId, the metadata to check in Monitor or
Insight). Say what happens if the step runs twice.