Metadata-Version: 2.5
Name: klozeo
Version: 0.2.0
Summary: Official Python SDK for the Klozeo Lead Management API
Project-URL: Homepage, https://klozeo.com
Project-URL: Documentation, https://docs.klozeo.com
Project-URL: Repository, https://github.com/lbframe/klozeo-sdk-python
Project-URL: Bug Tracker, https://github.com/lbframe/klozeo-sdk-python/issues
Author-email: Klozeo <hello@klozeo.com>
License: MIT
License-File: LICENSE
Keywords: api,crm,klozeo,leads,sdk
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: httpx>=0.27
Requires-Dist: pydantic>=2.0
Description-Content-Type: text/markdown

# Klozeo Python SDK

Official Python client for the [Klozeo](https://klozeo.com) Lead Management API.

French B2B deduplication: set `siren` to a valid 9-digit SIREN or 14-digit SIRET.
The API validates checksums (Luhn, or digit sum divisible by 5 for La Poste SIRETs), stores the SIREN, and merges within the account after email
and before source_id. Invalid values return 400; `and.eq.siren.732829320` filters by SIREN.

## Installation

```bash
pip install klozeo
```

Requires Python 3.10+.

## Quick Start

```python
from klozeo import Klozeo, Lead

client = Klozeo("sk_live_your_api_key")

# Create a lead
resp = client.create(Lead(
    name="Acme Corporation",
    source="website",
    city="San Francisco",
    email="contact@acme.com",
    rating=4.5,
    tags=["enterprise", "saas"],
))
print(f"Created: {resp.id}")

# List with filters
from klozeo import city, rating, SortField, SortOrder

result = client.list(
    city().eq("Berlin"),
    rating().gte(4.0),
    sort_by=SortField.RATING,
    sort_order=SortOrder.DESC,
    limit=20,
)
for lead in result.leads:
    print(f"{lead.name} — score: {lead.score}")

# Paginate automatically
for lead in client.iterate(city().eq("Berlin")):
    print(lead.name)
```

## Async Client

```python
import asyncio
from klozeo import AsyncKlozeo, Lead

async def main():
    async with AsyncKlozeo("sk_live_your_api_key") as client:
        resp = await client.create(Lead(name="Acme", source="website"))
        async for lead in client.iterate(city().eq("Berlin")):
            print(lead.name)

asyncio.run(main())
```

## Error Handling

```python
from klozeo import NotFoundError, RateLimitedError, ForbiddenError, KlozeoError

try:
    lead = client.get("cl_nonexistent")
except NotFoundError:
    print("Lead not found")
except RateLimitedError as e:
    print(f"Rate limited. Retry after {e.retry_after}s")
except ForbiddenError:
    print("Leads limit reached — upgrade your plan")
except KlozeoError as e:
    print(f"HTTP {e.status_code}: {e.message}")
```

## Links

- Documentation: https://docs.klozeo.com
- API Reference: https://docs.klozeo.com/api/leads
- PyPI: https://pypi.org/project/klozeo

## License

MIT. See [LICENSE](LICENSE).

### Empty filter values

An explicit empty string keeps its value segment: `name().contains("")`
serializes as `and.contains.name.`, and `city().eq("")` as `and.eq.city.`.
Operators without a value, such as `city().is_empty()`, still serialize without
a trailing dot. If a search box is empty and you want no filtering, omit that
optional filter rather than relying on the API to ignore malformed filters.

## Notes pagination

Notes are returned newest first (descending `created_at`), then by descending
`id` when timestamps are equal.

The existing notes list method returns all notes by following server cursors in
pages of 50. For bounded reads use `list_notes_page(lead_id, limit=20, cursor=cursor)` (also available on the async client).
The page includes notes, a continuation cursor and a has-more flag. 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).


### Batch update/delete results

For batch update and delete, inspect `results[]`: only affected leads have `success: true`. Missing IDs and IDs outside your account both return `success: false, message: "not found"`. The existing HTTP 207 status applies whenever any item fails (including all items). Grouped webhooks include only successful IDs and their actual count; no event is emitted when all items fail.

Duplicate creates merge custom attributes by exact name: add absent names, update
values of the same type, retain other attributes. The HTTP merge response (and
batch success item) adds `attribute_changes`: entries contain `name`, `action`
(`added`, `updated`, `ignored`) and, when ignored, `reason` (`type_mismatch` or
`ambiguous_name`). See [API merge contract](../../docs/api/api_reference.md).

SIREN/SIRET values must use ASCII digits without spaces or dots.

## Field locks

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

```python
lead = client.lock_field("cl_01234567-...", "city")
lead.locked_fields  # ["city"]

resp = client.create(Lead(name="Acme Corporation", source="import", email="contact@acme.com", city="Nice"))
resp.skipped_locked_fields  # ["city"]: the merge kept the stored city

client.unlock_field("cl_01234567-...", "city")
```

Lockable fields: `source`, `description`, `address`, `city`, `state`, `country`, `postal_code`, `phone`, `email`, `website`, `rating`, `review_count`, `category`, `tags`, `source_id`, `siren`, `logo_url`. Batch create items carry `skipped_locked_fields` too. `locked_fields` is read-only: `create` never sends it.

## Lead history

`client.list_changes(lead_id)` returns a lead's history as a list of `LeadChange`, newest first. It returns 50 entries by default and up to 100 with `limit`. A `limit` outside 1 to 100 returns 50. There is no cursor. `actions` keeps only the actions you name, as a list or as one name. The filter applies before `limit`, so frequent `scored` entries do not crowd out the others. `AsyncKlozeo` has the same method.

```python
changes = client.list_changes(
    "cl_01234567-...",
    limit=20,
    actions=["created", "updated", "merged"],
)

for change in changes:
    print(change.action, change.created_at, change.api_key_id or change.actor_id)
```

Each entry has an `id`, an `action` and a `created_at` (Unix time). `actor_id` is the member who made the change, when known. `api_key_id` is the API key behind a write made with a key, and it stays after the key is revoked. For such a write, `actor_id` 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`. `action` and `channel` also accept a value that a later API version adds, so an older SDK keeps reading the history.

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 `changed_fields`, the names of the fields that changed.

See [List Lead Changes](https://docs.klozeo.com/api/leads/#list-lead-changes).

## Safe retries

A create can time out after Klozeo has saved it. Pass `idempotency_key` and retry the same request with the same API key while Klozeo retains the result. The retry writes nothing again. It works on `create`, `batch_create` and `create_note`, as a keyword argument. `AsyncKlozeo` takes it too.

```python
resp = client.create(
    Lead(name="Acme Corporation", source="import", email="contact@example.com"),
    idempotency_key="import-42-row-7",
)

client.batch_create(leads, idempotency_key="import-42")

client.create_note(
    "cl_01234567-...",
    "Asked for a quote.",
    idempotency_key="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`, `5xx`, network errors and timeouts 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 is raised 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 is raised as a `BadRequestError`.

```python
from klozeo import KlozeoError

try:
    client.create(lead, idempotency_key="import-42-row-7")
except KlozeoError as e:
    if e.code == "idempotency_key_in_progress":
        pass  # Wait a moment, then send the same request with the same key.
```

See [Retries and idempotency](https://docs.klozeo.com/guides/retries-and-idempotency/).
