campai-api 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,344 @@
1
+ Metadata-Version: 2.4
2
+ Name: campai-api
3
+ Version: 0.1.0
4
+ Summary: Idiomatic, type-safe Python SDK for the Campai REST API.
5
+ Author: Stephan Lukasczyk
6
+ Author-email: Stephan Lukasczyk <stephan@dante.de>
7
+ License-Expression: EUPL-1.2
8
+ Requires-Dist: httpx>=0.27.0
9
+ Requires-Python: >=3.12
10
+ Description-Content-Type: text/markdown
11
+
12
+ <!--
13
+ SPDX-FileCopyrightText: 2026 Stephan Lukasczyk <stephan@dante.de>
14
+
15
+ SPDX-License-Identifier: EUPL-1.2
16
+ -->
17
+
18
+ # campai-api
19
+
20
+ Idiomatic, lightweight, and type-safe Python SDK for the [Campai REST API](https://cloud.campai.com/api).
21
+
22
+ [![Python 3.12+](https://img.shields.io/badge/python-3.12+-blue.svg)](https://www.python.org/downloads/)
23
+ [![Strict Typing](https://img.shields.io/badge/typing-strict-brightgreen.svg)](https://github.com/astral-sh/ty)
24
+
25
+ ---
26
+
27
+ ## Features
28
+
29
+ - **Minimal Dependencies**: Strictly limited to a single runtime dependency (`httpx>=0.27.0`).
30
+ - **Dual Native Clients**: Synchronous (`CampaiClient`) and asynchronous (`AsyncCampaiClient`) with native context
31
+ managers (`with` / `async with`) and explicit lifecycle methods (`close()` / `aclose()`).
32
+ - **Domain-Scoped Namespaces**: Logical grouping of endpoints under `client.auth`, `client.members`, `client.finance`,
33
+ and `client.webhooks`.
34
+ - **Pure Slotted Dataclasses**: Response and request structures built with standard library
35
+ `@dataclass(slots=True, kw_only=True)` for lightweight performance and full autocompletion.
36
+ - **Accurate OpenAPI Contracts**: Built against Campai's live OpenAPI specification (`https://cloud.campai.com/api`),
37
+ preserving exact payload constraints, integer cent amounts, and path structures.
38
+ - **Typed Error Hierarchy**: Clear exception mapping for HTTP status codes (e.g., `AuthenticationError` for 401,
39
+ `NotFoundError` for 404, `RateLimitError` for 429).
40
+
41
+ ---
42
+
43
+ ## Installation
44
+
45
+ ```bash
46
+ # Using uv (recommended)
47
+ uv add campai-api
48
+
49
+ # Using pip
50
+ pip install campai-api
51
+
52
+ # Install from source / Git repository
53
+ pip install git+https://codeberg.org/stephanlukasczyk/campai-api.git
54
+ ```
55
+
56
+ ---
57
+
58
+ ## Supported Endpoints & Coverage
59
+
60
+ Campai's OpenAPI specification defines ~664 API paths. This SDK provides complete, high-level typed bindings for the
61
+ core business resources:
62
+
63
+ | Domain Namespace | Endpoints & Routes | Supported Capabilities |
64
+ |:------------------|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:---------------------------------------------------------------------------------------------------|
65
+ | `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. |
66
+ | `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. |
67
+ | `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). |
68
+ | `client.webhooks` | `POST /{orgId}/oldContacts/{id}/triggerWebhooks`<br>`POST /{orgId}/oldMembers/{id}/triggerWebhooks` | Triggering webhook dispatches (`created`, `updated`, `deleted`) for contacts and members. |
69
+
70
+ > **Note**: For specialised or legacy endpoints outside these core modules, the underlying transport engine
71
+ > (`client.transport.request(...)`) can be used directly with full authentication and error mapping.
72
+
73
+ ---
74
+
75
+ ## Quick Start
76
+
77
+ ### Synchronous Client (`CampaiClient`)
78
+
79
+ ```python
80
+ from campai_api import (
81
+ Address,
82
+ CampaiClient,
83
+ ContactCreateRequest,
84
+ InvoiceCreateRequest,
85
+ InvoicePositionRequest,
86
+ PersonCreateInput,
87
+ )
88
+
89
+ with CampaiClient(api_key="your_campai_api_key") as client:
90
+ # 1. Retrieve API key and organisation details
91
+ info = client.auth.get_info()
92
+ org_id = info.organization
93
+ print(f"Authenticated with organisation: {org_id}")
94
+
95
+ # 2. Retrieve active mandates
96
+ mandates_resp = client.auth.list_mandates(org_id)
97
+ mandate_id = mandates_resp.mandates[0].id
98
+
99
+ # 3. List CRM contacts / members
100
+ contacts_resp = client.members.list(
101
+ organization_id=org_id,
102
+ mandate_id=mandate_id,
103
+ limit=20,
104
+ search_term="Mustermann",
105
+ )
106
+ for contact in contacts_resp.contacts:
107
+ print(f"Contact: {contact.name} ({contact.id})")
108
+
109
+ # 4. Create a new contact
110
+ new_contact = client.members.create(
111
+ organization_id=org_id,
112
+ mandate_id=mandate_id,
113
+ contact=ContactCreateRequest(
114
+ type="person",
115
+ person=PersonCreateInput(
116
+ title="Dr.",
117
+ first_name="Erika",
118
+ last_name="Mustermann",
119
+ gender=None,
120
+ birthdate=None,
121
+ ),
122
+ ),
123
+ )
124
+ print(f"Created contact ID: {new_contact.id}")
125
+
126
+ # 5. Create an invoice in the finance module (amounts in cents)
127
+ invoice_result = client.finance.create_invoice(
128
+ organization_id=org_id,
129
+ mandate_id=mandate_id,
130
+ invoice=InvoiceCreateRequest(
131
+ draft=False,
132
+ address=Address(
133
+ address_line="Musterstr. 1",
134
+ zip="10115",
135
+ city="Berlin",
136
+ country="DE",
137
+ ),
138
+ delivery_date_type="delivery",
139
+ title="Annual Membership Fee 2026",
140
+ intro="Thank you for being a valued member.",
141
+ account=8400,
142
+ receipt_date="2026-01-01",
143
+ due_date="2026-01-31",
144
+ positions=[
145
+ InvoicePositionRequest(
146
+ description="Annual Membership Fee",
147
+ unit_amount=12000, # 120.00 EUR in integer cents
148
+ account=8400,
149
+ quantity=1.0,
150
+ )
151
+ ],
152
+ ),
153
+ )
154
+ print(f"Created invoice receipt ID: {invoice_result.id}")
155
+ ```
156
+
157
+ ### Asynchronous Client (`AsyncCampaiClient`)
158
+
159
+ ```python
160
+ import asyncio
161
+ from campai_api import AsyncCampaiClient
162
+
163
+
164
+ async def main() -> None:
165
+ async with AsyncCampaiClient(api_key="your_campai_api_key") as client:
166
+ # Retrieve organisation and mandates
167
+ info = await client.auth.get_info()
168
+ mandates_resp = await client.auth.list_mandates(info.organization)
169
+ mandate_id = mandates_resp.mandates[0].id
170
+
171
+ # Async list contacts
172
+ response = await client.members.list(
173
+ organization_id=info.organization,
174
+ mandate_id=mandate_id,
175
+ limit=50,
176
+ )
177
+ print(f"Found {response.count} contacts.")
178
+
179
+
180
+ asyncio.run(main())
181
+ ```
182
+
183
+ ---
184
+
185
+ ## Architecture & Important API Concepts
186
+
187
+ ### 1. Default Server URL & Authentication
188
+
189
+ - **Default Base URL**: `https://cloud.campai.com/api` (the `/api` path prefix is automatically preserved and validated
190
+ against path-traversal attacks).
191
+ - **Authentication**: All API requests inject the `X-API-Key` header with your token.
192
+
193
+ ### 2. Organization and Mandate Scoping
194
+
195
+ Campai operates on a multi-tenant structure where CRM contacts, receipts, and invoices are partitioned under both an
196
+ **organisation ID** and a **mandate ID**:
197
+
198
+ - Obtain your organisation ID via `client.auth.get_info().organization`.
199
+ - List available mandates via `client.auth.list_mandates(org_id)` or fetch a specific mandate with
200
+ `client.auth.get_mandate(org_id, mandate_id)`.
201
+ - Pass `organization_id` and `mandate_id` as path arguments to scoped operations in `client.members` and
202
+ `client.finance`.
203
+
204
+ ### 3. List Operations are POST Endpoints
205
+
206
+ In the Campai REST API, listing queries (such as contacts or receipts) are HTTP `POST` requests sending a JSON body
207
+ containing pagination (`limit`, `offset`), search parameters (`searchTerm`), and filters (`types`, `segments`,
208
+ `teamId`). The SDK handles this seamlessly:
209
+
210
+ ```python
211
+ results = client.members.list(
212
+ organization_id=org_id,
213
+ mandate_id=mandate_id,
214
+ limit=50,
215
+ offset=0,
216
+ search_term="Tennis",
217
+ return_count=True,
218
+ )
219
+ ```
220
+
221
+ ### 4. Monetary Amounts in Integer Cents
222
+
223
+ All currency amounts in invoices and receipts (e.g. `unit_amount`, `discount`, `total_gross_amount`) are represented as
224
+ **integer cents** (e.g., `1250` represents `12.50 EUR`) in accordance with Campai's schema.
225
+
226
+ ### 5. Partial Contact Updates vs. Clearing Nulls
227
+
228
+ - **Typed Models (Sparse Updates)**: Using `ContactUpdateRequest` serializes only non-`None` attributes, ensuring
229
+ unmentioned fields are not overwritten or wiped:
230
+ ```python
231
+ client.members.update(
232
+ org_id,
233
+ mandate_id,
234
+ contact_id,
235
+ ContactUpdateRequest(contact_type="member"),
236
+ )
237
+ ```
238
+ - **Raw Dictionary Escape Hatch**: To explicitly set a field to `null` (e.g. clearing an address), pass a dictionary
239
+ payload:
240
+ ```python
241
+ client.members.update(
242
+ org_id,
243
+ mandate_id,
244
+ contact_id,
245
+ {"address": None},
246
+ )
247
+ ```
248
+
249
+ ### 6. Webhooks Scope & Limitations
250
+
251
+ - Campai's OpenAPI specification defines endpoints for **triggering** existing webhooks
252
+ (`POST /{organizationId}/oldContacts/{contactId}/triggerWebhooks` and `oldMembers`):
253
+ ```python
254
+ from campai_api.models import WebhookTriggerEvent
255
+
256
+ client.webhooks.trigger_contact_webhooks(
257
+ organization_id=org_id,
258
+ contact_id=contact_id,
259
+ event=WebhookTriggerEvent.UPDATED, # or "updated", "created", "deleted"
260
+ )
261
+ ```
262
+ - **Note**: Webhook subscription management (creating, listing, or deleting webhook subscription endpoints) is **not**
263
+ specified in Campai's OpenAPI specification and is therefore outside the scope of this SDK.
264
+
265
+ ### 7. Session Lifecycle & Ownership
266
+
267
+ - When `CampaiClient` / `AsyncCampaiClient` creates its own transport session, exiting context managers or calling
268
+ `close()` / `aclose()` cleanly closes all HTTP connection pools.
269
+ - When an external `httpx.Client`, `httpx.AsyncClient`, or `SyncTransport` / `AsyncTransport` is injected, the SDK does
270
+ **not** close the injected instance on `close()`, giving full lifecycle control to the caller.
271
+ - Calling any request on a closed client raises a typed `CampaiError`.
272
+
273
+ ---
274
+
275
+ ## Configuration Options
276
+
277
+ Both `CampaiClient` and `AsyncCampaiClient` accept optional configuration parameters:
278
+
279
+ ```python
280
+ from campai_api import CampaiClient
281
+
282
+ client = CampaiClient(
283
+ api_key="your_api_key",
284
+ base_url="https://cloud.campai.com/api", # Default production endpoint
285
+ timeout=60.0, # Request timeout in seconds
286
+ headers={"X-App-Name": "BillingWorker"}, # Additional default headers
287
+ # client=httpx.Client(...), # Optional custom httpx.Client injection
288
+ )
289
+ ```
290
+
291
+ ---
292
+
293
+ ## Error Handling
294
+
295
+ All SDK exceptions inherit from `CampaiError`:
296
+
297
+ ```python
298
+ from campai_api import CampaiClient
299
+ from campai_api.exceptions import (
300
+ AuthenticationError,
301
+ CampaiAPIError,
302
+ CampaiNetworkError,
303
+ NotFoundError,
304
+ RateLimitError,
305
+ )
306
+
307
+ with CampaiClient(api_key="invalid_key") as client:
308
+ try:
309
+ info = client.auth.get_info()
310
+ except AuthenticationError as exc:
311
+ print(f"Invalid API Key (HTTP 401): {exc.message}")
312
+ except NotFoundError as exc:
313
+ print(f"Resource not found (HTTP 404): {exc.message}")
314
+ except RateLimitError as exc:
315
+ print(f"Rate limited (HTTP 429): retry after {exc.retry_after} seconds")
316
+ except CampaiAPIError as exc:
317
+ print(f"API Error {exc.status_code}: {exc.message}")
318
+ except CampaiNetworkError as exc:
319
+ print(f"Network / connection error: {exc}")
320
+ ```
321
+
322
+ ---
323
+
324
+ ## Development & Testing
325
+
326
+ ```bash
327
+ # Run test suite
328
+ uv run --frozen pytest
329
+
330
+ # Run strict type checking with ty
331
+ uv run --frozen ty check
332
+
333
+ # Run linter and formatter checks with ruff
334
+ uv run --frozen ruff check .
335
+ uv run --frozen ruff format --check .
336
+ ```
337
+
338
+ ---
339
+
340
+ ## License
341
+
342
+ Created from Campai's [OpenAPI](https://cloud.campai.com/api/openapi.json) specification with the aid of
343
+ [Junie](https://junie.jetbrains.com).
344
+ Licensed under [EUPL-1.2](LICENSE.txt).
@@ -0,0 +1,21 @@
1
+ campai_api/__init__.py,sha256=SKn6Qdx7kk9c0L5f5ZSEj7svngGmyRcTGKo_hF3xsj8,3870
2
+ campai_api/async_client.py,sha256=oUcDRRNGH6hId5s7ZyMd-7XGV0WbtWZD0HqVh_U4fF0,4680
3
+ campai_api/auth.py,sha256=of5fmT-BVYWyua0wUJ0fIzFL79MQBzA-c63yHbF6y0c,1376
4
+ campai_api/client.py,sha256=Ucm0n64bXfMUPzUACSIFETHE_sJdtKjpB8B2uhn6nQM,4339
5
+ campai_api/exceptions.py,sha256=oOZsL9mpBFuJAvhkR-6zlnmym05ZgNnUpYCOUyXpqwM,7998
6
+ campai_api/models/__init__.py,sha256=8oTAungX952Gst98i658AcxpInLUkajV-GNXpq-MeDw,2033
7
+ campai_api/models/auth.py,sha256=C9YYUl9NwHaUgvBRl4XF10P29EVoukqcyIJjqBDM1E0,2321
8
+ campai_api/models/finance.py,sha256=OXHpcPjr_dzH2LwG3GSqbZQhjk7_p5TpGNmfrSv5zFs,8127
9
+ campai_api/models/members.py,sha256=5TXs98nbbRgWh6avX_bzChs7d_l9mDyWECGZwe6XSEM,7999
10
+ campai_api/models/webhooks.py,sha256=-DqSgUJQGqPlcaj68UplwjoljVhoVkHp5nNi0ArW5rU,935
11
+ campai_api/resources/__init__.py,sha256=dUtoKd3d8FdObzdknJpQbJhgF3Dk52eGSI-u629hgSA,818
12
+ campai_api/resources/auth.py,sha256=lk4CcCZHPncQRl4hAA1xJ2Lf2uPWsvSMtNd4-LOz43k,4358
13
+ campai_api/resources/base.py,sha256=HIFLZRKIdIiMJGrPmXnt-OE6D0ZdbViRQqYzmGyxqO4,1217
14
+ campai_api/resources/finance.py,sha256=RUtRwKynIYPWDdv403r-XT2eOaCyrXu98It0EIT2218,6696
15
+ campai_api/resources/members.py,sha256=FFjP9FyjlJRr2NWdkNz7MLQsju_a71gnfZRlehlG7R0,7246
16
+ campai_api/resources/webhooks.py,sha256=GNV-Td2uD_4cpNree6iAWG7HSz85jLbpl2GkQgM3i1M,3862
17
+ campai_api/serialization.py,sha256=XfamJmszFSxgdt2S5umZBH-ZReVEB0uQKPpDHdpF6OM,13913
18
+ campai_api/transport.py,sha256=vm0EhI4lgJuaD1bVsnltzxDcqWX7_zJT9LcAniCIrHI,18258
19
+ campai_api-0.1.0.dist-info/WHEEL,sha256=-gI5GRFdiNNn2CFz-ptlExISMINC-k8bFxeojAlHbrM,81
20
+ campai_api-0.1.0.dist-info/METADATA,sha256=-ltKzkgKA8tzz36_BbI0X363M5vg5ttFlvCDHp8VrrI,12534
21
+ campai_api-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.13.10
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any