Python SDK

leadveyor is the official client for Python 3.9 and later. It has a sync and an async client, a method for every endpoint, and response objects with type annotations for your editor and mypy. Its only dependency is httpx. It works with Django, Flask, FastAPI and plain scripts.

pip install leadveyor

Package: leadveyor on PyPI · Source: github.com/leadveyor/leadveyor-python · Releases. Questions and bugs: GitHub issues or support@leadveyor.com.

Quick start

from leadveyor import Leadveyor

lv = Leadveyor()  # reads LEADVEYOR_API_KEY; or Leadveyor("lv_live_…")

inbound = lv.inbounds.create(
    text="Hi, we need catering for 80 guests on 12 March in Richmond. Budget around $6k.",
    wait=True,  # wait for scoring instead of getting a webhook later
)
lead = inbound.leads[0] if inbound.leads else None
if lead:
    print(lead.evaluation.tier, lead.evaluation.score)

Create a key in the console or through the API. Without an argument, the client reads the LEADVEYOR_API_KEY environment variable.

Async

AsyncLeadveyor has the same methods; await them.

import asyncio
from leadveyor import AsyncLeadveyor

async def main() -> None:
    async with AsyncLeadveyor() as lv:
        inbound = await lv.inbounds.create(text="Hi, need a plumber tomorrow", wait=True)
        async for lead in lv.leads.list(tier="hot"):
            print(lead.id, lead.evaluation.score)

asyncio.run(main())

Resources

Methods follow the API one to one and have the same names as in the TypeScript SDK, in snake_case. Path IDs are positional. Everything else is a keyword argument named exactly like the API field (externalId=, sourceId=), so the API reference applies as is.

Methods
lv.inboundscreate, list, retrieve, reprocess
lv.leadslist, retrieve, list_evaluations, record_outcome, clear_outcome
lv.contactslist, retrieve, update, list_leads
lv.profileslist, create, retrieve, delete, validate, generate, generate_criterion, save_draft, update_draft, discard_draft, publish, activate, list_versions, retrieve_version
lv.templateslist, retrieve
lv.sourceslist, create, retrieve, update, delete
lv.destinationslist, create, retrieve, update, delete, rotate_secret, test, list_deliveries, retry_delivery
lv.eventslist, retrieve
lv.workspaceslist, create, retrieve, update
lv.api_keyslist, create, revoke
lv.billingretrieve, checkout, change_plan, portal, set_spend_limit
lv.usageretrieve: this period's leads against the plan
lv.reportsretrieve: a workspace's results for a period (Reports); compare_workspaces: all workspaces side by side
lv.evaluate()Score a message without saving anything (Evaluate)
# Record what happened to a lead — this is what teaches scoring what "good" means
lv.leads.record_outcome("lead_2Ph6Tc9Ks4Wm1Lx7Qv3Nb8Dr", status="won", amount=6200)

# Send a form submission; safe to repeat with the same externalId
lv.inbounds.create(fields={"name": "Ann Lee", "email": "ann@example.com", "guests": 80}, externalId="form-4711")

# Profile documents are passed as a dict
lv.profiles.create(document, publish=True)

An argument you leave out is not sent. None is sent as JSON null: for example, lv.billing.set_spend_limit(spendLimitUsd=None) removes the limit.

Responses

Responses are dicts whose fields can also be read as attributes.

lead = lv.leads.retrieve("lead_2Ph6Tc9Ks4Wm1Lx7Qv3Nb8Dr")  # leadveyor.models.Lead
lead.evaluation.tier          # "hot"
lead["evaluation"]["score"]   # 90
lead.to_dict()                # plain dicts
json.dumps(lead)              # works: it is a dict

Every object has a class in leadveyor.models (Lead, Inbound, Profile, Source and so on) with type annotations. A field the API left out reads as None.

Pagination

List methods return a page. Iterating it goes through every item and fetches the next pages as needed. See Pagination.

# This page
page = lv.leads.list(tier="hot", limit=50)
page.data, page.has_more, page.next_cursor

# Every item
for lead in lv.leads.list(outcome="none"):
    print(lead.id, lead.evaluation.score)

# Up to N items as a list
recent = lv.events.list(type="lead.*").to_list(limit=500)

With the async client, await lv.leads.list() returns the first page, async for lead in lv.leads.list() goes through every item, and await lv.leads.list().to_list(limit=500) collects up to N items.

Webhooks

Verify the Leadveyor-Signature header against the raw request body. Parsed and re-encoded JSON has different bytes, so the signature will not match. See Webhooks.

Flask

import os
from flask import Flask, request
from leadveyor import SignatureVerificationError, Webhook

app = Flask(__name__)

@app.post("/leadveyor-webhook")
def leadveyor_webhook():
    try:
        event = Webhook.construct_event(
            request.get_data(),                          # raw bytes
            request.headers.get("Leadveyor-Signature"),
            os.environ["LEADVEYOR_WEBHOOK_SECRET"],      # whsec_…
        )
    except SignatureVerificationError:
        return "", 400
    if event.type == "lead.scored":
        save_lead(event.data.object)                     # leadveyor.models.Lead
    return "", 200

FastAPI

import os
from fastapi import FastAPI, HTTPException, Request
from leadveyor import SignatureVerificationError, Webhook

app = FastAPI()

@app.post("/leadveyor-webhook")
async def leadveyor_webhook(request: Request):
    try:
        event = Webhook.construct_event(
            await request.body(),
            request.headers.get("leadveyor-signature"),
            os.environ["LEADVEYOR_WEBHOOK_SECRET"],
        )
    except SignatureVerificationError:
        raise HTTPException(status_code=400)
    if event.type == "lead.outcome_recorded":
        print(event.data.object.outcome.status, "was", (event.data.previous.outcome or {}).get("status"))
    return {}

In Django, use request.body and request.headers.get("Leadveyor-Signature"), and exempt the view from CSRF.

Webhook.verify(...) returns a bool instead of raising. Webhook.generate_test_header(payload, secret) signs a payload the way Leadveyor does, for your tests.

Workspaces

A workspace key works in its own workspace. With an account-wide key (agencies, several clients), choose the workspace:

client = lv.with_workspace("ws_1Bq7Xn4KpRz9Lc2Vt6Hy0Mde")  # every request
lv.leads.list(workspace="ws_…")                             # one request

Errors

Failed calls raise a subclass of leadveyor.LeadveyorError. See Errors.

ClassWhen
InvalidRequestError400: invalid parameters; e.errors lists every field problem
AuthenticationError401: missing, invalid or revoked key
PermissionDeniedError403: the key's permission or workspace doesn't allow it
NotFoundError404
ConflictError409
QuotaExceededError402: the plan's leads for this period are used up (Plans and limits); not retried
RateLimitError429, after the automatic retries
APIError5xx
APIConnectionError / APITimeoutErrorthe API could not be reached / no answer in time
from leadveyor import NotFoundError

try:
    lead = lv.leads.retrieve("lead_2Ph6Tc9Ks4Wm1Lx7Qv3Nb8Dr")
except NotFoundError:
    lead = None
# e.status_code, e.type, e.code, e.param, e.request_id (quote it to support)

Retries and timeouts

  • 429 responses are retried for every method, honouring Retry-After.
  • 5xx responses and network errors are retried for GET, PUT, PATCH and DELETE, for evaluate() and profiles.validate(), and for inbounds.create() with an externalId (the API returns the original inbound for a repeated ID). Other POSTs are not retried on them, because the request may already have been applied.
  • Two retries by default, with exponential backoff.
lv = Leadveyor(max_retries=4, timeout=30)
lv.evaluate(text=text, timeout=120)

Options

OptionDefault
api_keyLEADVEYOR_API_KEY
workspace—Leadveyor-Workspace for account-wide keys
base_urlhttps://core.leadveyor.comor LEADVEYOR_BASE_URL
timeout60seconds per attempt
max_retries2
http_clientnew httpx.Clientyour own httpx.Client / httpx.AsyncClient (proxies, tests)
default_headers—added to every request

Per-request keyword arguments on every method: workspace, timeout, max_retries, extra_headers. lv.with_options(timeout=5) returns a client with changed options.

Test mode

Keys starting with lv_test_ work with test data, kept apart from live data (livemode: false). lv.livemode tells which kind of key the client uses.

Was this page helpful?