Metadata-Version: 2.4
Name: campai-api
Version: 0.1.0
Summary: Idiomatic, type-safe Python SDK for the Campai REST API.
Author: Stephan Lukasczyk
Author-email: Stephan Lukasczyk <stephan@dante.de>
License-Expression: EUPL-1.2
Requires-Dist: httpx>=0.27.0
Requires-Python: >=3.12
Description-Content-Type: text/markdown

<!--
SPDX-FileCopyrightText: 2026 Stephan Lukasczyk <stephan@dante.de>

SPDX-License-Identifier: EUPL-1.2
-->

# campai-api

Idiomatic, lightweight, and type-safe Python SDK for the [Campai REST API](https://cloud.campai.com/api).

[![Python 3.12+](https://img.shields.io/badge/python-3.12+-blue.svg)](https://www.python.org/downloads/)
[![Strict Typing](https://img.shields.io/badge/typing-strict-brightgreen.svg)](https://github.com/astral-sh/ty)

---

## Features

- **Minimal Dependencies**: Strictly limited to a single runtime dependency (`httpx>=0.27.0`).
- **Dual Native Clients**: Synchronous (`CampaiClient`) and asynchronous (`AsyncCampaiClient`) with native context
  managers (`with` / `async with`) and explicit lifecycle methods (`close()` / `aclose()`).
- **Domain-Scoped Namespaces**: Logical grouping of endpoints under `client.auth`, `client.members`, `client.finance`,
  and `client.webhooks`.
- **Pure Slotted Dataclasses**: Response and request structures built with standard library
  `@dataclass(slots=True, kw_only=True)` for lightweight performance and full autocompletion.
- **Accurate OpenAPI Contracts**: Built against Campai's live OpenAPI specification (`https://cloud.campai.com/api`),
  preserving exact payload constraints, integer cent amounts, and path structures.
- **Typed Error Hierarchy**: Clear exception mapping for HTTP status codes (e.g., `AuthenticationError` for 401,
  `NotFoundError` for 404, `RateLimitError` for 429).

---

## Installation

```bash
# Using uv (recommended)
uv add campai-api

# Using pip
pip install campai-api

# Install from source / Git repository
pip install git+https://codeberg.org/stephanlukasczyk/campai-api.git
```

---

## Supported Endpoints & Coverage

Campai's OpenAPI specification defines ~664 API paths. This SDK provides complete, high-level typed bindings for the
core business resources:

| Domain Namespace  | Endpoints & Routes                                                                                                                                                                                                                            | Supported Capabilities                                                                             |
|:------------------|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:---------------------------------------------------------------------------------------------------|
| `client.auth`     | `GET /apiKey/info`<br>`GET /organizations/{orgId}`<br>`POST /organizations/{orgId}/mandates/list`<br>`GET /organizations/{orgId}/mandates/{mandateId}`                                                                                        | API key capability lookup, organization details, mandate listing, and retrieval.                   |
| `client.members`  | `POST /{orgId}/{mandateId}/crm/contacts/list`<br>`POST /{orgId}/{mandateId}/crm/contacts`<br>`GET /{orgId}/{mandateId}/crm/contacts/{id}`<br>`POST /{orgId}/{mandateId}/crm/contacts/{id}`<br>`DELETE /{orgId}/{mandateId}/crm/contacts/{id}` | CRM contact & member search, pagination, full creation, sparse/partial updates, and deletion.      |
| `client.finance`  | `GET /{orgId}/finance/settings`<br>`POST /{orgId}/finance/settings`<br>`POST /{orgId}/{mandateId}/finance/receipts/list`<br>`POST /{orgId}/{mandateId}/receipts/invoice`<br>`POST /{orgId}/{mandateId}/receipts/invoice/{id}`                 | Financial settings, receipt queries/pagination, and invoice creation & updates (amounts in cents). |
| `client.webhooks` | `POST /{orgId}/oldContacts/{id}/triggerWebhooks`<br>`POST /{orgId}/oldMembers/{id}/triggerWebhooks`                                                                                                                                           | Triggering webhook dispatches (`created`, `updated`, `deleted`) for contacts and members.          |

> **Note**: For specialised or legacy endpoints outside these core modules, the underlying transport engine
> (`client.transport.request(...)`) can be used directly with full authentication and error mapping.

---

## Quick Start

### Synchronous Client (`CampaiClient`)

```python
from campai_api import (
  Address,
  CampaiClient,
  ContactCreateRequest,
  InvoiceCreateRequest,
  InvoicePositionRequest,
  PersonCreateInput,
)

with CampaiClient(api_key="your_campai_api_key") as client:
  # 1. Retrieve API key and organisation details
  info = client.auth.get_info()
  org_id = info.organization
  print(f"Authenticated with organisation: {org_id}")

  # 2. Retrieve active mandates
  mandates_resp = client.auth.list_mandates(org_id)
  mandate_id = mandates_resp.mandates[0].id

  # 3. List CRM contacts / members
  contacts_resp = client.members.list(
    organization_id=org_id,
    mandate_id=mandate_id,
    limit=20,
    search_term="Mustermann",
  )
  for contact in contacts_resp.contacts:
    print(f"Contact: {contact.name} ({contact.id})")

  # 4. Create a new contact
  new_contact = client.members.create(
    organization_id=org_id,
    mandate_id=mandate_id,
    contact=ContactCreateRequest(
      type="person",
      person=PersonCreateInput(
        title="Dr.",
        first_name="Erika",
        last_name="Mustermann",
        gender=None,
        birthdate=None,
      ),
    ),
  )
  print(f"Created contact ID: {new_contact.id}")

  # 5. Create an invoice in the finance module (amounts in cents)
  invoice_result = client.finance.create_invoice(
    organization_id=org_id,
    mandate_id=mandate_id,
    invoice=InvoiceCreateRequest(
      draft=False,
      address=Address(
        address_line="Musterstr. 1",
        zip="10115",
        city="Berlin",
        country="DE",
      ),
      delivery_date_type="delivery",
      title="Annual Membership Fee 2026",
      intro="Thank you for being a valued member.",
      account=8400,
      receipt_date="2026-01-01",
      due_date="2026-01-31",
      positions=[
        InvoicePositionRequest(
          description="Annual Membership Fee",
          unit_amount=12000,  # 120.00 EUR in integer cents
          account=8400,
          quantity=1.0,
        )
      ],
    ),
  )
  print(f"Created invoice receipt ID: {invoice_result.id}")
```

### Asynchronous Client (`AsyncCampaiClient`)

```python
import asyncio
from campai_api import AsyncCampaiClient


async def main() -> None:
  async with AsyncCampaiClient(api_key="your_campai_api_key") as client:
    # Retrieve organisation and mandates
    info = await client.auth.get_info()
    mandates_resp = await client.auth.list_mandates(info.organization)
    mandate_id = mandates_resp.mandates[0].id

    # Async list contacts
    response = await client.members.list(
      organization_id=info.organization,
      mandate_id=mandate_id,
      limit=50,
    )
    print(f"Found {response.count} contacts.")


asyncio.run(main())
```

---

## Architecture & Important API Concepts

### 1. Default Server URL & Authentication

- **Default Base URL**: `https://cloud.campai.com/api` (the `/api` path prefix is automatically preserved and validated
  against path-traversal attacks).
- **Authentication**: All API requests inject the `X-API-Key` header with your token.

### 2. Organization and Mandate Scoping

Campai operates on a multi-tenant structure where CRM contacts, receipts, and invoices are partitioned under both an
**organisation ID** and a **mandate ID**:

- Obtain your organisation ID via `client.auth.get_info().organization`.
- List available mandates via `client.auth.list_mandates(org_id)` or fetch a specific mandate with
  `client.auth.get_mandate(org_id, mandate_id)`.
- Pass `organization_id` and `mandate_id` as path arguments to scoped operations in `client.members` and
  `client.finance`.

### 3. List Operations are POST Endpoints

In the Campai REST API, listing queries (such as contacts or receipts) are HTTP `POST` requests sending a JSON body
containing pagination (`limit`, `offset`), search parameters (`searchTerm`), and filters (`types`, `segments`,
`teamId`). The SDK handles this seamlessly:

```python
results = client.members.list(
  organization_id=org_id,
  mandate_id=mandate_id,
  limit=50,
  offset=0,
  search_term="Tennis",
  return_count=True,
)
```

### 4. Monetary Amounts in Integer Cents

All currency amounts in invoices and receipts (e.g. `unit_amount`, `discount`, `total_gross_amount`) are represented as
**integer cents** (e.g., `1250` represents `12.50 EUR`) in accordance with Campai's schema.

### 5. Partial Contact Updates vs. Clearing Nulls

- **Typed Models (Sparse Updates)**: Using `ContactUpdateRequest` serializes only non-`None` attributes, ensuring
  unmentioned fields are not overwritten or wiped:
  ```python
  client.members.update(
    org_id,
    mandate_id,
    contact_id,
    ContactUpdateRequest(contact_type="member"),
  )
  ```
- **Raw Dictionary Escape Hatch**: To explicitly set a field to `null` (e.g. clearing an address), pass a dictionary
  payload:
  ```python
  client.members.update(
    org_id,
    mandate_id,
    contact_id,
    {"address": None},
  )
  ```

### 6. Webhooks Scope & Limitations

- Campai's OpenAPI specification defines endpoints for **triggering** existing webhooks
  (`POST /{organizationId}/oldContacts/{contactId}/triggerWebhooks` and `oldMembers`):
  ```python
  from campai_api.models import WebhookTriggerEvent

  client.webhooks.trigger_contact_webhooks(
    organization_id=org_id,
    contact_id=contact_id,
    event=WebhookTriggerEvent.UPDATED,  # or "updated", "created", "deleted"
  )
  ```
- **Note**: Webhook subscription management (creating, listing, or deleting webhook subscription endpoints) is **not**
  specified in Campai's OpenAPI specification and is therefore outside the scope of this SDK.

### 7. Session Lifecycle & Ownership

- When `CampaiClient` / `AsyncCampaiClient` creates its own transport session, exiting context managers or calling
  `close()` / `aclose()` cleanly closes all HTTP connection pools.
- When an external `httpx.Client`, `httpx.AsyncClient`, or `SyncTransport` / `AsyncTransport` is injected, the SDK does
  **not** close the injected instance on `close()`, giving full lifecycle control to the caller.
- Calling any request on a closed client raises a typed `CampaiError`.

---

## Configuration Options

Both `CampaiClient` and `AsyncCampaiClient` accept optional configuration parameters:

```python
from campai_api import CampaiClient

client = CampaiClient(
  api_key="your_api_key",
  base_url="https://cloud.campai.com/api",  # Default production endpoint
  timeout=60.0,  # Request timeout in seconds
  headers={"X-App-Name": "BillingWorker"},  # Additional default headers
  # client=httpx.Client(...),               # Optional custom httpx.Client injection
)
```

---

## Error Handling

All SDK exceptions inherit from `CampaiError`:

```python
from campai_api import CampaiClient
from campai_api.exceptions import (
  AuthenticationError,
  CampaiAPIError,
  CampaiNetworkError,
  NotFoundError,
  RateLimitError,
)

with CampaiClient(api_key="invalid_key") as client:
  try:
    info = client.auth.get_info()
  except AuthenticationError as exc:
    print(f"Invalid API Key (HTTP 401): {exc.message}")
  except NotFoundError as exc:
    print(f"Resource not found (HTTP 404): {exc.message}")
  except RateLimitError as exc:
    print(f"Rate limited (HTTP 429): retry after {exc.retry_after} seconds")
  except CampaiAPIError as exc:
    print(f"API Error {exc.status_code}: {exc.message}")
  except CampaiNetworkError as exc:
    print(f"Network / connection error: {exc}")
```

---

## Development & Testing

```bash
# Run test suite
uv run --frozen pytest

# Run strict type checking with ty
uv run --frozen ty check

# Run linter and formatter checks with ruff
uv run --frozen ruff check .
uv run --frozen ruff format --check .
```

---

## License

Created from Campai's [OpenAPI](https://cloud.campai.com/api/openapi.json) specification with the aid of
[Junie](https://junie.jetbrains.com).
Licensed under [EUPL-1.2](LICENSE.txt).
