API guide
Recipes
Complete, end-to-end examples you can copy: click-to-call, call logging, SMS auto-reply, dialer campaigns, your own softphone and an AI agent that books appointments.
Each recipe uses the lexo() helper and the environment variables from Getting started, and the signature check from Webhooks.
A click-to-call button in your CRM#
Goal: a "Call" button next to every phone number in your CRM. The agent's LexoConnect phone rings, and when they pick up LexoConnect dials the customer.
You need: an API key with calls:write and users:read; each CRM user mapped to a LexoConnect user.
- Once, map your users to LexoConnect users by email:
const { items } = await lexo("GET", "/users");
const lexoUserByEmail = new Map(items.map((u) => [u.email.toLowerCase(), u.id]));- Add a server endpoint your button calls:
// Express. The browser sends { to } only; the server decides whose phone rings.
app.post("/api/click-to-call", requireLogin, express.json(), async (req, res) => {
const userId = lexoUserByEmail.get(req.user.email.toLowerCase());
if (!userId) return res.status(400).json({ error: "No LexoConnect phone for this user" });
try {
const call = await lexo("POST", "/calls/originate", { userId, to: req.body.to });
res.json({ callUuid: call.callUuid });
} catch (err) {
res.status(502).json({ error: String(err.message) });
}
});- In the page:
fetch("/api/click-to-call", {method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({to: "+12125550123"})}).
Variant: if the LexoConnect phone is embedded in your page (see Embedding), call phone.dial(number) directly instead.
Log every call into your CRM#
Goal: every call, its recording and the agent's outcome appear on the right customer in your CRM, within seconds.
You need: a webhook endpoint subscribed to call.ended, recording.ready and call.dispositioned; an API key with calls:read if you download recordings.
const seen = new Set(); // use a database table with a unique index in production
app.post("/lexo/webhooks", express.raw({ type: "application/json" }), async (req, res) => {
if (!verify(req.headers, req.body.toString("utf8"))) return res.sendStatus(401);
const id = req.headers["webhook-id"];
res.sendStatus(204);
if (seen.has(id)) return; // retries and replays reuse the same webhook-id
seen.add(id);
const { type, data } = JSON.parse(req.body);
const customer = data.direction === "inbound" ? data.from : data.to;
switch (type) {
case "call.ended":
await crm.upsertCallActivity({
externalId: data.id, phone: customer, direction: data.direction, status: data.status,
startedAt: data.startedAt, durationSec: data.durationSec, agentId: data.userId,
});
break;
case "recording.ready":
await crm.attachRecording({ externalId: data.callId, url: data.signedUrl }); // valid 24 hours: copy the file if you keep it
break;
case "call.dispositioned":
// data: callId, recordId, number, direction, agentId, dispositionId, disposition (label), outcome, note,
// followUpAt, campaignId, campaignLeadId, at
await crm.setOutcome({ phone: data.number, disposition: data.disposition, note: data.note, followUpAt: data.followUpAt });
break;
}
});Field names of call.dispositioned and the other events are listed with examples in the API reference. To fill gaps after an outage, page through GET /calls for the missing time range.
Receive an SMS and reply automatically#
Goal: answer "hours" questions by SMS automatically and leave everything else for the team.
You need: a webhook subscribed to message.received; an API key with messages:write.
app.post("/lexo/webhooks", express.raw({ type: "application/json" }), async (req, res) => {
if (!verify(req.headers, req.body.toString("utf8"))) return res.sendStatus(401);
res.sendStatus(204);
const { type, data } = JSON.parse(req.body);
if (type !== "message.received" || data.channel !== "sms") return;
const text = (data.message.body || "").toLowerCase();
if (text.includes("hours") || text.includes("open")) {
await lexo("POST", `/omni/conversations/${data.conversationId}/messages`, {
body: "We are open Monday to Friday, 9 am to 5 pm. Reply with your question and a person will answer.",
});
}
});Your own replies come back as outbound messages, not as message.received, so the bot cannot loop. Opt-out words (STOP, …) are handled by LexoConnect before your webhook sees them.
Start a dialer campaign from your system#
Goal: your system decides who to call today, LexoConnect dials them with its agents, and the outcomes flow back.
You need: an API key with campaigns:write, campaigns:read and users:read; a webhook subscribed to campaign.lead.completed and call.dispositioned.
const { items: users } = await lexo("GET", "/users");
const agents = users.filter((u) => u.role === "agent" && u.status === "active").map((u) => u.id);
const campaign = await lexo("POST", "/campaigns", {
name: `Renewals ${new Date().toISOString().slice(0, 10)}`,
object: "lead", mode: "progressive",
windowStart: "09:00", windowEnd: "18:00", timezone: "America/New_York", useLeadTimezone: true,
agentIds: agents, maxAttempts: 3, retryMinutes: 90, amdEnabled: true, amdAction: "hangup",
});
const leads = await myDb.customersDueForRenewal(); // [{ name, phone, email }]
for (let i = 0; i < leads.length; i += 5000) {
const r = await lexo("POST", `/campaigns/${campaign.id}/leads/upload`, { rows: leads.slice(i, i + 5000) });
console.log(r); // { added, duplicates, dnc, invalid }
}
await lexo("POST", `/campaigns/${campaign.id}/status`, { status: "running" });When each lead is finished, campaign.lead.completed tells you its final status, result, dispositionId and attempts; call.dispositioned carries the agent's note and follow-up. Pause the campaign at the end of the day with {"status": "paused"}, or mark it completed.
Build your own softphone UI#
Goal: a phone that looks like your product, inside your product.
- Your server mints a webphone token for the signed-in user (
POST /webphone/tokens, scopewebphone). - The browser exchanges it for SIP credentials (
POST /webphone/session) and registers to LexoConnect over WebSocket with SIP.js (or any SIP-over-WebSocket library). - Draw your own dial pad, incoming-call banner and call controls on top of the SIP.js session events.
- Use the REST API for what is not in SIP:
POST /calls/current/transfer,.../recording,.../park,GET /crm/lookupfor screen pops, andPOST /calls/wrapupfor outcomes.
The complete client code is in Embedding → Build your own phone UI. If you only need a working phone, the ready-made iframe or SDK takes minutes instead.
An AI agent that books appointments#
Goal: an AI receptionist answers your number around the clock, checks free slots in your booking system and books the appointment.
You need: an API key with ai:write and numbers:write; an HTTPS endpoint in your booking system.
- Create the agent with two HTTP actions and a human fallback:
const agent = await lexo("POST", "/ai-agents", {
name: "Booking assistant",
language: "en",
greeting: "Hi, thanks for calling Northwind Dental. Would you like to book an appointment?",
instructions:
"Help callers book a cleaning. Ask for their name and preferred day. Call find_slots, offer at most three " +
"slots, then call book_appointment with the slot the caller chose. Confirm the booking and say goodbye.",
maxDurationSec: 600,
tools: {
hangup: { enabled: true },
transfer: { enabled: true, targets: [{ name: "Reception", description: "A person, for anything else", type: "queue", value: receptionQueueId, mode: "warm" }] },
httpActions: [
{
name: "find_slots",
description: "Find free appointment slots on a day.",
url: "https://booking.example.com/lexo/ACTION_TOKEN/find-slots",
method: "POST",
parameters: { type: "object", properties: { date: { type: "string", description: "YYYY-MM-DD" } }, required: ["date"] },
},
{
name: "book_appointment",
description: "Book a slot returned by find_slots.",
url: "https://booking.example.com/lexo/ACTION_TOKEN/book",
method: "POST",
parameters: {
type: "object",
properties: { slotId: { type: "string" }, patientName: { type: "string" } },
required: ["slotId", "patientName"],
},
},
],
},
});- Answer the actions in your booking system. The agent reads your answer back to the caller:
app.post("/lexo/:token/find-slots", express.json(), async (req, res) => {
if (req.params.token !== process.env.ACTION_TOKEN) return res.sendStatus(404);
const { date } = req.body.data.arguments;
const slots = await booking.freeSlots(date); // [{ id, label: "Tuesday 18 November, 3 pm" }]
res.json({ slots: slots.slice(0, 3) });
});
app.post("/lexo/:token/book", express.json(), async (req, res) => {
if (req.params.token !== process.env.ACTION_TOKEN) return res.sendStatus(404);
const { slotId, patientName } = req.body.data.arguments;
const caller = req.body.data.from;
const ok = await booking.book({ slotId, patientName, phone: caller });
res.json(ok ? { booked: true, message: "The appointment is booked." } : { booked: false, message: "That slot was just taken." });
});- Route the number to the agent (only after hours, if you prefer, with a schedule):
curl -X PATCH "$LEXO_URL/api/v1/numbers/NUMBER_ID" \
-H "Authorization: Bearer $LEXO_API_KEY" -H "Content-Type: application/json" \
-d '{"routeType": "ai_agent", "routeId": "AGENT_ID"}'- Subscribe to
ai.call.endedto store the transcript, summary and outcome of every AI call.
Answer each action within 8 seconds; keep the answer short, because the agent reads it to the caller.