Integration recipes

Worked examples that connect our APIs to the tools you already use

Last reviewed

Before you start

Every recipe follows the same four rules:

  • Build with a test key. Test keys reach demo data only. See What is an API? for which APIs offer them.
  • Keep keys on your server. Read them from the environment, never from code, a web page or a shared spreadsheet. See Keeping your API keys safe.
  • Wait when told to. On a 429, wait for the seconds in Retry-After before trying again. See API rate limits.
  • Check every webhook. Verify the webhook-signature header before acting on a delivery, and turn away old timestamps. See API errors and request IDs for what a failed call returns.

The recipes build on these two helpers: a request that backs off on a 429, and a webhook signature check that works for every API.

curl

# Keep the key off the command line, where other users of the machine can
# see it: write the header to a private curl config file once.
umask 077
printf 'header = "Authorization: Bearer %s"\n' "$API_KEY" > api.curlrc

# --retry makes curl wait and try again on a 429, and it
# honours the Retry-After header the API sends with it.
curl --retry 5 "https://thewill.ai/api/v1/portfolio/ext/holdings/" \
  --config api.curlrc

Python

import base64
import hashlib
import hmac
import os
import random
import time

import requests

BASE_URL = "https://thewill.ai/api/v1"
session = requests.Session()
# The key lives in the server's environment, never in code or a browser.
session.headers["Authorization"] = f"Bearer {os.environ['API_KEY']}"


def get_with_backoff(url, params=None, max_attempts=5):
    """GET url, waiting as the API asks whenever it answers 429."""
    for attempt in range(max_attempts):
        response = session.get(url, params=params, timeout=30)
        if response.status_code != 429:
            response.raise_for_status()
            return response.json()
        retry_after = response.headers.get("Retry-After", "")
        delay = int(retry_after) if retry_after.isdigit() else 2 ** attempt
        time.sleep(delay + random.uniform(0, 1))
    raise RuntimeError(f"Still rate limited after {max_attempts} attempts: {url}")


def verify_webhook(raw_body, secret, headers, tolerance_seconds=300):
    """True when a delivery is signed with your endpoint secret and is recent."""
    timestamp = headers["webhook-timestamp"]
    if abs(time.time() - int(timestamp)) > tolerance_seconds:
        return False  # too old: a captured delivery being replayed
    signed = f"{headers['webhook-id']}.{timestamp}.".encode() + raw_body
    expected = base64.b64encode(
        hmac.new(secret.encode("utf-8"), signed, hashlib.sha256).digest()
    ).decode()
    return any(
        hmac.compare_digest(f"v1,{expected}", candidate)
        for candidate in headers["webhook-signature"].split(" ")
    )

Node.js

import crypto from "node:crypto";

export const BASE_URL = "https://thewill.ai/api/v1";
// The key lives in the server's environment, never in code or a browser.
const HEADERS = { Authorization: `Bearer ${process.env.API_KEY}` };
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

export async function getWithBackoff(url, maxAttempts = 5) {
  for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
    const response = await fetch(url, { headers: HEADERS });
    if (response.status !== 429) {
      if (!response.ok) throw new Error(`${response.status} from ${url}`);
      return response.json();
    }
    const retryAfter = Number(response.headers.get("Retry-After"));
    const delay = retryAfter > 0 ? retryAfter : 2 ** attempt;
    await sleep((delay + Math.random()) * 1000);
  }
  throw new Error(`Still rate limited after ${maxAttempts} attempts: ${url}`);
}

export function verifyWebhook(rawBody, secret, headers, toleranceSeconds = 300) {
  const timestamp = headers["webhook-timestamp"];
  if (Math.abs(Date.now() / 1000 - Number(timestamp)) > toleranceSeconds) return false;
  const expected = crypto
    .createHmac("sha256", Buffer.from(secret, "utf8"))
    .update(`${headers["webhook-id"]}.${timestamp}.`)
    .update(rawBody)
    .digest("base64");
  const wanted = Buffer.from(`v1,${expected}`);
  return headers["webhook-signature"].split(" ").some((candidate) => {
    const given = Buffer.from(candidate);
    return given.length === wanted.length && crypto.timingSafeEqual(given, wanted);
  });
}

Keep a practice-management system in step

Firms and their software suppliers syncing clients, matters and appointments

API_KEY holds a professional key (pro:read). Build against a test key first.

  1. First run: walk the whole collection with cursor pagination, following next until it is null, and upsert every row by id.
  2. Store the newest updated_at you saw. Later runs pass it as updated_since, so you only fetch what changed.
  3. Register a webhook endpoint in the Developer hub. Verify every delivery, ignore a webhook-id you have already handled, then re-fetch the changed record.
  4. The same pattern works for matters, appointments, invoices and time entries.

curl

# First run: every client, oldest change first, 500 a page
curl --retry 5 "https://thewill.ai/api/v1/pro/ext/clients/?cursor=&page_size=500" \
  --config api.curlrc

# Later runs: only what changed since the newest updated_at you stored
curl --retry 5 "https://thewill.ai/api/v1/pro/ext/clients/?cursor=&updated_since=2026-01-31T09:00:00Z" \
  --config api.curlrc

Python

from flask import Flask, abort, request


def sync_clients(store):
    """Upsert every client changed since the last run."""
    url = f"{BASE_URL}/pro/ext/clients/"
    params = {"cursor": "", "page_size": 500}
    if store.last_seen:
        params["updated_since"] = store.last_seen
    while url:
        page = get_with_backoff(url, params)
        for client in page["results"]:
            store.upsert(client["id"], client)
            store.last_seen = max(store.last_seen or "", client["updated_at"])
        url, params = page["next"], None  # next already carries the cursor


app = Flask(__name__)


@app.post("/webhooks/practice")
def practice_webhook():
    if not verify_webhook(request.get_data(), os.environ["WEBHOOK_SECRET"], request.headers):
        abort(401)
    if not store.first_time_seen(request.headers["webhook-id"]):
        return "", 204  # a retry of a delivery you already handled
    queue_sync(request.get_json())
    return "", 204

Node.js

import express from "express";

export async function syncClients(store) {
  const params = new URLSearchParams({ cursor: "", page_size: "500" });
  if (store.lastSeen) params.set("updated_since", store.lastSeen);
  let url = `${BASE_URL}/pro/ext/clients/?${params}`;
  while (url) {
    const page = await getWithBackoff(url);
    for (const client of page.results) {
      await store.upsert(client.id, client);
      if (!store.lastSeen || client.updated_at > store.lastSeen) store.lastSeen = client.updated_at;
    }
    url = page.next; // next already carries the cursor
  }
}

const app = express();
// Verify against the raw bytes: parsing JSON first changes the body.
app.post("/webhooks/practice", express.raw({ type: "application/json" }), async (req, res) => {
  if (!verifyWebhook(req.body, process.env.WEBHOOK_SECRET, req.headers)) return res.sendStatus(401);
  if (await store.firstTimeSeen(req.headers["webhook-id"])) await queueSync(JSON.parse(req.body));
  return res.sendStatus(204);
});

Connect an HR or benefits platform

Employers and HR or benefits platforms offering the service to staff

SCIM calls use a provisioning token from Settings. Reporting calls put your corporate key (twcorp_) in API_KEY. They are separate on purpose.

  1. Create starters with SCIM. A leaver is switched off with active set to false, which frees the seat without deleting anything.
  2. Pull the roster and feature adoption on a schedule with your corporate key.
  3. Subscribe to corporate webhooks in Settings, and verify each delivery before acting on it.

curl

# A starter (provisioning token, not your API key)
curl -X POST "https://thewill.ai/api/v1/corporate/scim/v2/Users/" \
  --config scim.curlrc \
  -H "Content-Type: application/scim+json" \
  -d '{"schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
       "userName": "sam.patel@example.com",
       "name": {"givenName": "Sam", "familyName": "Patel"},
       "emails": [{"value": "sam.patel@example.com", "primary": true}]}'

# A leaver: switch the seat off
curl -X PATCH "https://thewill.ai/api/v1/corporate/scim/v2/Users/$USER_ID/" \
  --config scim.curlrc \
  -H "Content-Type: application/scim+json" \
  -d '{"schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
       "Operations": [{"op": "replace", "value": {"active": false}}]}'

# The reporting pull, with your corporate key
curl --retry 5 "https://thewill.ai/api/v1/corporate/ext/roster/" --config api.curlrc
curl --retry 5 "https://thewill.ai/api/v1/corporate/ext/feature-adoption/" --config api.curlrc

Python

scim = requests.Session()
scim.headers.update({
    "Authorization": f"Bearer {os.environ['SCIM_TOKEN']}",
    "Content-Type": "application/scim+json",
})


def add_starter(email, given_name, family_name):
    response = scim.post(f"{BASE_URL}/corporate/scim/v2/Users/", timeout=30, json={
        "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
        "userName": email,
        "name": {"givenName": given_name, "familyName": family_name},
        "emails": [{"value": email, "primary": True}],
    })
    response.raise_for_status()
    return response.json()["id"]  # keep it: the leaver call needs it


def remove_leaver(user_id):
    scim.patch(f"{BASE_URL}/corporate/scim/v2/Users/{user_id}/", timeout=30, json={
        "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
        "Operations": [{"op": "replace", "value": {"active": False}}],
    }).raise_for_status()


def monthly_report():
    return {
        "roster": get_with_backoff(f"{BASE_URL}/corporate/ext/roster/"),
        "adoption": get_with_backoff(f"{BASE_URL}/corporate/ext/feature-adoption/"),
    }

Node.js

const SCIM_HEADERS = {
  Authorization: `Bearer ${process.env.SCIM_TOKEN}`,
  "Content-Type": "application/scim+json",
};

export async function addStarter(email, givenName, familyName) {
  const response = await fetch(`${BASE_URL}/corporate/scim/v2/Users/`, {
    method: "POST",
    headers: SCIM_HEADERS,
    body: JSON.stringify({
      schemas: ["urn:ietf:params:scim:schemas:core:2.0:User"],
      userName: email,
      name: { givenName, familyName },
      emails: [{ value: email, primary: true }],
    }),
  });
  if (!response.ok) throw new Error(`SCIM create failed: ${response.status}`);
  return (await response.json()).id; // keep it: the leaver call needs it
}

export async function removeLeaver(userId) {
  const response = await fetch(`${BASE_URL}/corporate/scim/v2/Users/${userId}/`, {
    method: "PATCH",
    headers: SCIM_HEADERS,
    body: JSON.stringify({
      schemas: ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
      Operations: [{ op: "replace", value: { active: false } }],
    }),
  });
  if (!response.ok) throw new Error(`SCIM update failed: ${response.status}`);
}

export async function monthlyReport() {
  return {
    roster: await getWithBackoff(`${BASE_URL}/corporate/ext/roster/`),
    adoption: await getWithBackoff(`${BASE_URL}/corporate/ext/feature-adoption/`),
  };
}

Feed a personal-finance dashboard or spreadsheet

Individuals reading their own portfolio into a dashboard or spreadsheet

API_KEY holds a personal test key while you build. Swap in a live key when it works.

  1. Create a test key in the Developer hub. It only reaches demo data, so nothing real is at risk while you build.
  2. Run a small script on your own computer or server that saves the figures to a file your dashboard or spreadsheet imports.
  3. Do not paste the key into a spreadsheet formula or web page: anyone who can open the file could read it.

curl

curl --retry 5 "https://thewill.ai/api/v1/portfolio/ext/holdings/" --config api.curlrc
curl --retry 5 "https://thewill.ai/api/v1/portfolio/ext/analytics/allocation/" --config api.curlrc
curl --retry 5 "https://thewill.ai/api/v1/portfolio/ext/analytics/performance/" --config api.curlrc

Python

import json

snapshot = {
    "holdings": get_with_backoff(f"{BASE_URL}/portfolio/ext/holdings/"),
    "allocation": get_with_backoff(f"{BASE_URL}/portfolio/ext/analytics/allocation/"),
    "performance": get_with_backoff(f"{BASE_URL}/portfolio/ext/analytics/performance/"),
}
with open("portfolio-snapshot.json", "w", encoding="utf-8") as handle:
    json.dump(snapshot, handle, indent=2)

Node.js

import { writeFile } from "node:fs/promises";

const snapshot = {
  holdings: await getWithBackoff(`${BASE_URL}/portfolio/ext/holdings/`),
  allocation: await getWithBackoff(`${BASE_URL}/portfolio/ext/analytics/allocation/`),
  performance: await getWithBackoff(`${BASE_URL}/portfolio/ext/analytics/performance/`),
};
await writeFile("portfolio-snapshot.json", JSON.stringify(snapshot, null, 2));

Connect an AI assistant

Anyone giving an AI assistant or agent read access through MCP

API_KEY holds the key you give the assistant. Start with a test key and the fewest scopes it needs.

  1. Point any MCP client that speaks streamable HTTP at the MCP endpoint, with the key as a Bearer token.
  2. Each call is JSON-RPC 2.0 over POST. tools/list shows the tools this key may use.
  3. Revoke the key in the Developer hub to cut the assistant off at once.

curl

curl --retry 5 -X POST "https://thewill.ai/api/v1/mcp/" \
  --config api.curlrc \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  -d '{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}'

Python

response = session.post(
    f"{BASE_URL}/mcp/",
    json={"jsonrpc": "2.0", "id": 1, "method": "tools/list"},
    headers={"Accept": "application/json, text/event-stream"},
    timeout=30,
)
response.raise_for_status()
for tool in response.json()["result"]["tools"]:
    print(tool["name"], "-", tool.get("title", ""))

Node.js

const response = await fetch(`${BASE_URL}/mcp/`, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.API_KEY}`,
    "Content-Type": "application/json",
    Accept: "application/json, text/event-stream",
  },
  body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" }),
});
const { result } = await response.json();
for (const tool of result.tools) console.log(tool.name, "-", tool.title ?? "");

Trigger a no-code automation from a webhook

Teams wiring events into an automation tool that gives them a "catch hook" URL

API_KEY holds the key that owns the webhook endpoint. WEBHOOK_SECRET is that endpoint's signing secret.

  1. Most catch-hook URLs cannot check a signature. Put a small relay in front: it verifies the delivery, then forwards the body to the catch hook.
  2. Register the relay's address, not the catch hook's, as the webhook endpoint in the Developer hub.
  3. Send a test event to check the whole chain, then build the automation on the forwarded payload.

curl

# Send a test event to your endpoint, then check the automation ran
curl --retry 5 -X POST "https://thewill.ai/api/v1/portfolio/ext/webhooks/$ENDPOINT_ID/test/" \
  --config api.curlrc

Python

from flask import Flask, abort, request

app = Flask(__name__)


@app.post("/relay")
def relay():
    raw_body = request.get_data()
    if not verify_webhook(raw_body, os.environ["WEBHOOK_SECRET"], request.headers):
        abort(401)
    requests.post(
        os.environ["CATCH_HOOK_URL"],
        data=raw_body,
        headers={"Content-Type": "application/json"},
        timeout=10,
    ).raise_for_status()
    return "", 204

Node.js

import express from "express";

const app = express();
app.post("/relay", express.raw({ type: "application/json" }), async (req, res) => {
  if (!verifyWebhook(req.body, process.env.WEBHOOK_SECRET, req.headers)) return res.sendStatus(401);
  const forwarded = await fetch(process.env.CATCH_HOOK_URL, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: req.body,
  });
  return res.sendStatus(forwarded.ok ? 204 : 502);
});

Analytics, billing and invoices

What each API lets you read about money and usage

Personal (portfolio) API

How your portfolio is spread across asset types, and how it has performed:

  • GET /api/v1/portfolio/ext/analytics/allocation/
  • GET /api/v1/portfolio/ext/analytics/performance/

Professional API

Booking and revenue analytics, invoices and time entries:

  • GET /api/v1/pro/ext/booking-analytics/
  • GET /api/v1/pro/ext/revenue-analytics/
  • GET /api/v1/pro/ext/invoices/
  • GET /api/v1/pro/ext/time-entries/

Corporate reporting API

Your invoices from us and how staff are using each feature:

  • GET /api/v1/corporate/ext/invoices/
  • GET /api/v1/corporate/ext/feature-adoption/

Billing stays in your account

Paying for a plan, changing it and updating a payment method are not open to API keys. A personal subscription is managed only while signed in to your account. Corporate billing (plan, VAT details and payment method) is only for signed-in console admins, and a reporting key cannot open it. To read your corporate invoices from code, use GET /api/v1/corporate/ext/invoices/ above.

These account-only addresses refuse a reporting or personal key: /api/v1/corporate/billing/summary/, /api/v1/corporate/billing/invoices/, /api/v1/corporate/billing/payment-method/, /api/v1/subscriptions/subscribe/.

For every endpoint, open the reference for your API from Which API is for me?

Can’t find what you’re looking for?

Our support team is here to help. Contact us and we’ll get back to you as soon as possible.

Contact us

We use cookies to improve your experience. See our Cookie policy (opens in a new tab) for details.