Skip to content

Post Form Data to Your API and Handle Failures

A claims team submits a form. The workflow posts the form values to the team's own claims API. When the API rejects the request, the claim must not stop in an error state: it goes to a review task that shows the API's error text, a person fixes it, and the workflow tries again.

At a glance

  • Extension point Call External API with a Javascript preprocessor, a route, and a Custom Step
  • You need work-item fields Index.ClaimNumber, Index.ClaimAmount, Index.Urgent (a Boolean field, so "true" or "false"), Index.IncidentDate, and an index field SubmitError on the task's content type; your API's URL and auth header; permission to edit the workflow.
  • Teaches A typed JSON body, routing on the status code, and keeping the error text for a reviewer.

Set it up

  1. In the Workflow designer, add a Call External API step named "Submit Claim".
  2. Select the gear icon next to Body, choose Javascript, and paste the body script below.
  3. Set the other settings:
Setting Value
External API URL https://api.example.com/claims
REST Verb POST
HTTP Headers Your API's auth header, for example x-api-key
Body Type JSON
Response Metadata Key SubmitResponse
Timeout 60
Retries 1
Error Behavior Continue
  1. From "Submit Claim", draw the success route to the next normal step, with the Javascript route condition below.
  2. Draw a second route to a Custom Step named "Keep Submit Error" and make it the default route. Paste the Custom Step script below.
  3. From "Keep Submit Error", route to the review task. From the review task, route back to "Submit Claim".
  4. Add SubmitError to the content type the task uses, so the reviewer sees it. Save the workflow.

With Continue, a non-2xx response runs the routes instead of stopping the work item. Do not add Content-Type to the headers; the Body Type sets it.

Script

If a trigger form started the work item, the values are in bucket Trigger instead of Index: change the bucket name in the scripts.

Body preprocessor

Javascript preprocessor: Body of Submit Claim
(function () {
  var f = workItem.Metadata["Index"] || {};

  function toNumber(s) {
    var n = parseFloat(String(s || "").replace(/[^0-9.\-]/g, ""));
    return isNaN(n) ? null : n;
  }
  function toBoolean(s) {
    return String(s || "").toLowerCase() === "true";
  }
  function toIsoDate(s) {
    var d = new Date(s);
    return isNaN(d.getTime()) ? null : d.toISOString();
  }

  return JSON.stringify({
    claimNumber: f["ClaimNumber"] || "",
    claimAmount: toNumber(f["ClaimAmount"]),
    urgent: toBoolean(f["Urgent"]),
    incidentDate: toIsoDate(f["IncidentDate"]),
    sourceWorkItemId: workItem.WorkItemId
  });
})()

Success route condition

Javascript route: Submit Succeeded
(function () {
  var api = workItem.Metadata["ApiResults"] || {};
  var code = parseInt(api["LastHttpStatusCode"] || "0", 10);
  return code >= 200 && code < 300;
})()

Keep Submit Error step

Custom Step: Keep Submit Error
// Copies the API's answer into an index field that the review task shows,
// and clears the status so a stale code cannot pass the next attempt.
var api = batch.Metadata["ApiResults"] || {};
var err = batch.Metadata["Error"] || {};
var code = api["LastHttpStatusCode"] || "none";
var body = api["SubmitResponse"] || err["LastErrorMessage"] || "No response body";

builder.SetBatchMetadata("Index", "SubmitError", ("HTTP " + code + ": " + body).substring(0, 2000));
builder.SetBatchMetadata("ApiResults", "LastHttpStatusCode", "");

How it works

  • Metadata values are strings, but the API expects a JSON number, a JSON boolean and an ISO 8601 timestamp. A Liquid template would send "Urgent": "True" or break on a quote.
  • The Javascript preprocessor converts each value and JSON.stringify escapes the text.
  • Match the property names and casing to your API's contract. Many APIs reject ClaimNumber when they expect claimNumber.
  • The step writes ApiResults.LastHttpStatusCode and ApiResults.SubmitResponse for every response. With Error Behavior Continue, the routes run even on a 400.
  • The success route is true only for a 2xx status. Every other case, including a timeout that wrote no status, takes the default route to "Keep Submit Error".
  • The Custom Step clears LastHttpStatusCode, so when the claim loops back, an old 200 cannot make a timed-out retry look successful.

Test it

  1. Submit a valid claim. Check ApiResults.LastHttpStatusCode = 200 on the work item in Monitor or Insight, and that the claim reached the next normal step.
  2. Submit a claim with an amount your API rejects. Check that the work item reached the review task.

You should see

the rejected claim in the review task with Index.SubmitError such as HTTP 400: {"error":"claimAmount must be greater than 0"}, and the valid claim on the normal path.

What can go wrong

Watch out

  • 400 Bad Request. The payload does not match the contract: wrong property casing, a boolean sent as "True", a date that is not ISO 8601, a missing required field. Read ApiResults.SubmitResponse.
  • 401 Unauthorized. The auth header is missing, wrong or expired, often after a key rotation. See Rotate an API Token Without Breaking Workflows.
  • 403 Forbidden. An API gateway or firewall in front of your API blocks the request, or the key lacks the scope. Calls come from the KnowledgeLake cloud, not from your network. If your gateway allows callers by IP address, ask KnowledgeLake support for the outbound addresses.
  • 413 Payload Too Large. The body is over your gateway's limit. Send ids and short values, not document content. Let your API fetch files through the KnowledgeLake API.
  • "Api domain is not valid". The host resolves to a private address. Use the public host name.
  • The work item stops in an error state instead of reaching the task. Error Behavior is still Stop. Set Continue.

Variations

  • Send the claim id back. If your API returns the new claim's id, parse ApiResults.SubmitResponse in a Custom Step on the success path and write it to Index.ExternalClaimId. See Use an API Result in a Custom Step.
  • Record the outcome for reporting. Add a Custom Event step on each path with Scopes claim, submitted and claim, rejected.