Skip to main content

campai-api

Idiomatic, lightweight, and type-safe Python SDK for the Campai REST API.

Python 3.12+ Strict Typing


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

# 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
GET /organizations/{orgId}
POST /organizations/{orgId}/mandates/list
GET /organizations/{orgId}/mandates/{mandateId}
API key capability lookup, organization details, mandate listing, and retrieval.
client.members POST /{orgId}/{mandateId}/crm/contacts/list
POST /{orgId}/{mandateId}/crm/contacts
GET /{orgId}/{mandateId}/crm/contacts/{id}
POST /{orgId}/{mandateId}/crm/contacts/{id}
DELETE /{orgId}/{mandateId}/crm/contacts/{id}
CRM contact & member search, pagination, full creation, sparse/partial updates, and deletion.
client.finance GET /{orgId}/finance/settings
POST /{orgId}/finance/settings
POST /{orgId}/{mandateId}/finance/receipts/list
POST /{orgId}/{mandateId}/receipts/invoice
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
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)

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)

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:

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:
    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:
    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):
    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:

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:

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

# 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 specification with the aid of Junie. Licensed under EUPL-1.2.

Metadata

Release files for campai-api 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for campai-api 0.1.0
File Size Uploaded Provenance Actions
campai_api-0.1.0.tar.gz 24.4 kB Without provenance Details for campai_api-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for campai-api 0.1.0
File Interpreter ABI Platform Actions
campai_api-0.1.0-py3-none-any.whl Python 3 none any Details for campai_api-0.1.0-py3-none-any.whl

Total release size: 56.6 kB

Release files / campai_api-0.1.0.tar.gz

Download URL campai_api-0.1.0.tar.gz
Size 24.4 kB
Tags Source
SHA-256 checksum
How to use checksums
f0b853f30fea210179afaa07f432928553c7325cb96d92de11c8f7154d37b654
BLAKE2b-256 checksum
How to use checksums
af78bb014501e5701d6c9a5c2733a0ba3046d114d368b8274f671ea2370d4ab8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.10 {"installer":{"name":"uv","version":"0.13.10","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / campai_api-0.1.0-py3-none-any.whl

Download URL campai_api-0.1.0-py3-none-any.whl
Size 32.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
4927cfe3eb1349323c797cbeaf389531559c6ed6fb6ad2b39a7b7896732504fc
BLAKE2b-256 checksum
How to use checksums
a183b2718775e4cb6e22db32f8021dc87b81d8b24d83b628d6807dd89fd9c704
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.10 {"installer":{"name":"uv","version":"0.13.10","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for campai-api 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page