Skip to content

TypeScript SDK

TypeScript and Python are the maintained SDKs. The Go and Rust SDKs are unmaintained since 27 October 2026; use this SDK or the REST API.

Terminal window
npm install @klozeo/sdk

Requires Node.js 18+ (or any modern browser). Ships ESM + CJS with full TypeScript types.

import { Klozeo } from "@klozeo/sdk";
const client = new Klozeo("sk_live_your_api_key");
// Create a lead
const resp = await client.leads.create({
name: "Acme Corporation",
source: "website",
city: "San Francisco",
rating: 4.5,
tags: ["enterprise", "saas"],
});
console.log(`Created: ${resp.id}`);
// List with filters
import { city, rating } from "@klozeo/sdk/filters";
const leads = await client.leads.list({
filters: [city().eq("Berlin"), rating().gte(4.0)],
sortBy: "rating",
sortOrder: "desc",
limit: 20,
});
// Iterate all pages automatically
for await (const lead of client.leads.iterate({
filters: [city().eq("Berlin")],
})) {
console.log(lead.name);
}
// Export to CSV
import { ExportFormat } from "@klozeo/sdk";
const csv = await client.leads.export(ExportFormat.CSV);
const client = new Klozeo("sk_live_your_api_key", {
baseUrl: "https://custom.api.com", // default: https://api.klozeo.com/api/v1
timeout: 30_000, // ms, default 30 000
maxRetries: 3, // retries on 429 / 5xx
});
import {
city, country, rating, tags,
or, attr,
} from "@klozeo/sdk/filters";
const leads = await client.leads.list({
filters: [
city().eq("Paris"),
or().city().eq("Lyon"), // OR city = Lyon
rating().gte(4.0),
tags().contains("enterprise"),
attr("industry").eq("Software"), // dynamic attribute
],
});
import { textAttr, numberAttr, boolAttr, listAttr } from "@klozeo/sdk";
await client.leads.create({
name: "Acme",
source: "web",
attributes: [
textAttr("industry", "Software"),
numberAttr("employees", 500),
boolAttr("verified", true),
listAttr("products", ["CRM", "ERP"]),
],
});
import { KlozeoError, RateLimitedError, UnauthorizedError, NotFoundError } from "@klozeo/sdk";
try {
const lead = await client.leads.create({ name: "Acme", source: "web" });
} catch (err) {
if (err instanceof RateLimitedError) {
console.log(`Rate limited. Retry after ${err.retryAfter}s`);
} else if (err instanceof UnauthorizedError) {
console.log("Invalid or revoked API key");
} else if (err instanceof NotFoundError) {
console.log("Lead not found");
} else if (err instanceof KlozeoError) {
console.log(`API error ${err.statusCode}: ${err.message}`);
}
}
const note = await client.notes.create(leadId, "Called back — very interested.");
const notes = await client.notes.list(leadId);
await client.notes.delete(noteId);

client.leads.listChanges(leadId) returns a lead’s history, newest first. It returns 50 entries by default and up to 100 with limit. limit goes from 1 to 100 (default 50). A higher value is capped at 100; a value below 1 uses 50. There is no cursor. actions keeps only the actions you name. The filter applies before limit, so frequent scored entries do not crowd out the others.

const { changes } = await client.leads.listChanges(leadId, {
limit: 20,
actions: ["created", "updated", "merged"],
});
for (const change of changes) {
console.log(change.action, change.createdAt, change.apiKeyId ?? change.actorId);
}

Each entry has an id, an action and a createdAt (Unix time). actorId is the member who made the change, when known. apiKeyId is the API key behind a write made with a key, and it stays after the key is revoked. For such a write, actorId is the account owner.

before and after hold snapshots with snake_case keys. Lead snapshots omit assignee and do_not_contact_by. Note snapshots omit author. A create has no before. A delete has no after. A scored entry holds only score. A note.created, note.updated or note.deleted entry holds the note. assigned and unassigned entries hold neither.

reason says why an entry exists, for example attribute:industry. assignee is the new assignee’s email on an assigned entry. channel says how the lead arrived, on created and merged entries: api, api_batch, mcp_classic, dashboard, import or save_leads.

It works for a deleted lead. Klozeo keeps its history for 30 days. A daily job then erases before, after and assignee, so they are gone within 31 days of the deletion. The entries stay, with changedFields, the names of the fields that changed. → List Lead Changes

// Create up to 100 leads at once
const results = await client.leads.batchCreate(leads);
// Delete by IDs
await client.leads.batchDelete(["cl_...", "cl_..."]);

A create can time out after Klozeo has saved it. Pass idempotencyKey and retry the same request with the same API key while Klozeo retains the result. The retry writes nothing again. It works on leads.create, leads.batchCreate and notes.create.

const resp = await client.leads.create(
{ name: "Acme Corporation", source: "import", email: "[email protected]" },
{ idempotencyKey: "import-42-row-7" },
);
await client.leads.batchCreate(leads, { idempotencyKey: "import-42" });
await client.notes.create(leadId, "Asked for a quote.", {
idempotencyKey: "import-42-row-7-note",
});

You choose the key. The SDK never makes one. A key is 1 to 200 printable ASCII characters. Use a new key for each new request. Klozeo keeps the result for 30 days. Using another API key, or retrying after the stored result is removed, starts a new request.

The SDK’s own retries on 429 and 5xx send the same key again.

A retry of a lead create returns the first result, even if the lead changed since. A retry of a note create returns the note as it is now. One key covers a whole batch. The SDK does not tell you whether a response is a replay.

A key problem arrives as a KlozeoError with a code:

  • idempotency_key_reused (409): the key was used with a different request. Nothing was written.
  • idempotency_key_in_progress (409): the first request is still running. Wait a moment, then send the same request with the same key.
  • NOTE_ALREADY_DELETED (410): the note was created, then deleted. No new note is written.
  • invalid_idempotency_key (400): the key is empty, too long or has other characters. It arrives as a BadRequestError.
import { KlozeoError } from "@klozeo/sdk";
try {
await client.leads.create(input, { idempotencyKey: "import-42-row-7" });
} catch (err) {
if (err instanceof KlozeoError && err.code === "idempotency_key_in_progress") {
// Wait a moment, then send the same request with the same key.
}
}

→ Retries and idempotency

Full source and examples: github.com/lbframe/klozeo-sdk-typescript

Package on npm: npmjs.com/package/@klozeo/sdk

The existing notes list method returns all notes by following server cursors in pages of 50. For bounded reads use notes.listPage(leadId, { limit: 20, cursor }). The page includes notes, a continuation cursor and a has-more flag (camelCase in TypeScript). Pass the cursor unchanged to read the next page. Iteration stops when has_more is false. A missing or empty cursor while more notes remain, repeated cursors and more than 10,000 pages raise an error rather than returning a silently truncated history. API limits are 1–50 (default 20).

Lock a field you have verified so that duplicate merges, imports and company enrichment never overwrite it. Explicit updates (leads.update, leads.batchUpdate) still write it. Both calls are idempotent, need the editor or owner role, and return the lead.

const lead = await client.leads.lockField("cl_01234567-...", "city");
lead.lockedFields; // ["city"]
const resp = await client.leads.create({ name: "Acme Corporation", source: "import", email: "[email protected]", city: "Nice" });
resp.skippedLockedFields; // ["city"]: the merge kept the stored city
await client.leads.unlockField("cl_01234567-...", "city");

See Field locks. Lockable fields: source, description, address, city, state, country, postal_code, phone, email, website, rating, review_count, category, tags, source_id, siren, logo_url. Use the API names (snake_case). Batch create items carry skippedLockedFields too.

Lock a custom attribute with leads.lockAttribute(id, attrId) and unlock it with leads.unlockAttribute(id, attrId). Take the attribute ID from lead.attributes in leads.get. Duplicate merges, imports and company enrichment then never write it, and a merge that sends it lists it in attributeChanges as ignored, with the reason locked. Both calls are idempotent, need an API key with the full scope, and return the attribute.

In this example the lead has a valid email and an existing industry attribute. The create sends that same email, so it merges into the lead, and the locked industry is ignored.

const leadId = "cl_01234567-...";
const lead = await client.leads.get(leadId);
lead.email; // "[email protected]"
const industry = lead.attributes?.find((a) => a.name === "industry");
const attr = await client.leads.lockAttribute(leadId, industry!.id!);
attr.locked; // true
const resp = await client.leads.create({ name: lead.name, source: "import", email: lead.email, attributes: [textAttr("industry", "Retail")] });
resp.duplicate; // true
resp.attributeChanges; // [{ name: "industry", action: "ignored", reason: "locked" }]
await client.leads.unlockAttribute(leadId, industry!.id!);

See Lock Attribute. locked is true only on a locked attribute, also in leads.get. It is read-only. Batch create items carry attributeChanges too.

The workspace lock policy lists the fields and custom attributes to freeze after their first value, on leads created after each name takes effect. client.lockPolicy.get() returns two lists, fields and attributes. Each entry has a name and effectiveAt, the time the name took effect, in Unix seconds. A full or read API key can read it.

client.lockPolicy.replace({ fields, attributes }) replaces the whole policy and returns the new one. Send both lists, even when one does not change, and [] to empty one. To add a name, send the current names with it. Only the owner and admins can replace the policy, and only the owner on the Free plan; from the SDK, that takes an API key with the full scope.

import { KlozeoError } from "@klozeo/sdk";
const policy = await client.lockPolicy.get();
policy.attributes; // [{ name: "utm_campaign", effectiveAt: 1794925800 }]
try {
const updated = await client.lockPolicy.replace({
fields: policy.fields.map((e) => e.name),
attributes: [...policy.attributes.map((e) => e.name), "utm_source"],
});
updated.attributes.map((e) => e.name); // ["utm_campaign", "utm_source"]: utm_campaign keeps its effectiveAt
} catch (err) {
if (err instanceof KlozeoError && err.code === "save_temporarily_unavailable") {
// Nothing was saved. Try the replace again later.
} else {
throw err;
}
}

fields takes the lockable fields listed above, by their API names (snake_case). attributes takes exact custom attribute names, case-sensitive, 1 to 255 characters each, at most 50. A name sent twice is stored once. A broken rule throws a BadRequestError and nothing is saved. A name already in the policy keeps its effectiveAt; a new name covers only leads created from then on. The policy never locks existing leads, and removing a name leaves the locks already set.

If the policy cannot be saved right now, the SDK retries on its own, like any 5xx, then throws a KlozeoError with statusCode 503 and code save_temporarily_unavailable. Nothing is saved.

See Lock policy. The AccountExport type describes the document client.account.export() returns, with lock_policy and statuses optional; account.export() still returns a Blob.