Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -551,6 +551,41 @@ client.delete_segment(segment_id)
* `add_customers_to_segment` and `remove_customers_from_segment` take up to 1000 identifiers per call, all of the kind `id_type` names (`"id"` by default, `"email"`, `"cio_id"` or `"phone"`). The API doesn't check that the people exist and doesn't create profiles.
* Only manual segments can be created, changed or deleted this way. `delete_segment` returns `None`; the API refuses to delete a segment that something still uses (see `get_segment_used_by`).

## Export data

Use the `APIClient` with an [app key](https://customer.io/docs/managing-credentials#app-api-keys) to export people or deliveries to a CSV file. An export runs in the background: start it, poll `get_export` until its `status` is `"done"`, then ask `download_export` for a link to the file. Each call returns the API's JSON as a dict.

```python
import time

from customerio import APIClient, Regions

client = APIClient("your API key", region=Regions.US)

export = client.create_customers_export(
{"and": [{"segment": {"id": 3}}]}, attributes=["email", "plan"]
)["export"]

while export["status"] == "pending":
time.sleep(10)
export = client.get_export(export["id"])["export"]

if export["status"] == "done":
print(client.download_export(export["id"])["url"])
```

* `create_customers_export(filters, attributes=None)` exports the people who match `filters`, built like the filter in `search_customers`. `attributes` adds columns.
* `create_deliveries_export(...)` exports messages. It takes keyword arguments only: one of `newsletter_id`, `campaign_id`, `action_id`, `template_id` or `transactional_message_id` to pick the source (with several, only the first of `action_id`, `campaign_id`, `template_id`, `newsletter_id`, `transactional_message_id` counts), and `start`, `end`, `attributes`, `metric` and `drafts`. Without `start` it covers the last 6 months, or all of a one-time send; ranges over 1 year are refused.
* `download_export` returns a link that expires after 15 minutes; it doesn't fetch the file.
* `list_exports()` returns the recent exports, newest first.

```python
response = client.create_deliveries_export(campaign_id=46, metric="delivered", start=1717200000)
export = response["export"]
```

With the one key `Client`, the same calls are on `cio.api_client`.

## Notes
- The Customer.io Python SDK depends on the [`Requests`](https://pypi.org/project/requests/) library which includes [`urllib3`](https://pypi.org/project/urllib3/) as a transitive dependency. The [`Requests`](https://pypi.org/project/requests/) library leverages connection pooling defined in [`urllib3`](https://pypi.org/project/urllib3/). [`urllib3`](https://pypi.org/project/urllib3/) only attempts to retry invocations of `HTTP` methods which are understood to be idempotent (See: [`Retry.DEFAULT_ALLOWED_METHODS`](https://github.com/urllib3/urllib3/blob/main/src/urllib3/util/retry.py#L184)). Since the `POST` method is not considered to be idempotent, any invocations which require `POST` are not retried.

Expand Down
100 changes: 100 additions & 0 deletions customerio/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -739,6 +739,106 @@ def delete_segment(self, segment_id):
def _segment_url(self, segment_id):
return f"{self.url}/v1/segments/{_path_segment('segment_id', segment_id)}"

def list_exports(self):
"""Return the recent exports in the workspace (``{"exports": [...]}``), newest first.

Each export has its ``id``, ``type`` (such as ``"customers"`` or
``"deliveries"``), ``status`` (``"pending"``, ``"done"`` or ``"failed"``) and
row ``total``. ``exports`` is ``None`` when there are none.
"""
resp = self.send_request("GET", self.url + "/v1/exports")
return resp.json()

def get_export(self, export_id):
"""Return the export with the given numeric id (``{"export": {...}}``).

Its ``status`` is ``"done"`` once the file is ready for
:meth:`download_export`.
"""
resp = self.send_request("GET", self._export_url(export_id))
return resp.json()

def download_export(self, export_id):
"""Return a signed link to an export's file (``{"url": "..."}``).

The link expires after 15 minutes, so fetch the file soon after; this call
doesn't download it. The API answers 404 while the export isn't ready and
410 once it has expired.
"""
resp = self.send_request("GET", self._export_url(export_id) + "/download")
return resp.json()

def create_customers_export(self, filters, attributes=None):
"""Start an export of the people who match a filter and return it.

``filters`` is a dict built from ``segment`` and ``attribute`` conditions,
combined with ``and``, ``or`` and ``not``, as in :meth:`search_customers`.
``attributes`` is an optional list of attribute names to add as columns. The
response is ``{"export": {...}}``; the export runs in the background, so poll
:meth:`get_export` with its ``id`` until its ``status`` is ``"done"``.
"""
if not isinstance(filters, dict) or not filters:
raise CustomerIOException("filters is required")
body = {"filters": filters}
if attributes is not None:
body["attributes"] = attributes
resp = self.send_request("POST", self.url + "/v1/exports/customers", body)
return resp.json()

def create_deliveries_export(
self,
*,
newsletter_id=None,
campaign_id=None,
action_id=None,
template_id=None,
transactional_message_id=None,
start=None,
end=None,
attributes=None,
metric=None,
drafts=None,
):
"""Start an export of deliveries (individual messages) and return it.

All arguments are optional keywords, left out of the request when ``None``.
The ids pick what to export from: a one-time send (``newsletter_id``), an
automation (``campaign_id``), one action (``action_id``), one message template
(``template_id``) or a transactional message (``transactional_message_id``).
Send one; if you send several, only the first of ``action_id``,
``campaign_id``, ``template_id``, ``newsletter_id`` and
``transactional_message_id`` counts. With none, the export holds every
delivery in the workspace for the time range.

``start`` and ``end`` are Unix timestamps of when deliveries were created.
Without ``start``, the export covers the last 6 months, or every delivery of a
one-time send; the API refuses a range longer than 1 year. ``attributes`` is
a list of person attribute names to add as columns, ``metric`` keeps only
deliveries with that metric (such as ``"delivered"`` or ``"clicked"``), and
``drafts=True`` exports drafts (messages not sent yet) instead of sent ones.

The response is ``{"export": {...}}``; poll :meth:`get_export` with its
``id`` until its ``status`` is ``"done"``.
"""
fields = {
"newsletter_id": newsletter_id,
"campaign_id": campaign_id,
"action_id": action_id,
"template_id": template_id,
"transactional_message_id": transactional_message_id,
"start": start,
"end": end,
"attributes": attributes,
"metric": metric,
"drafts": drafts,
}
body = {name: value for name, value in fields.items() if value is not None}
resp = self.send_request("POST", self.url + "/v1/exports/deliveries", body)
return resp.json()

def _export_url(self, export_id):
return f"{self.url}/v1/exports/{_path_segment('export_id', export_id)}"

def _build_session(self):
session = super()._build_session()
session.headers["Authorization"] = f"Bearer {self.key}"
Expand Down
134 changes: 134 additions & 0 deletions tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -837,6 +837,140 @@ def test_delete_segment_requires_id(self):
self.client.delete_segment(segment_id)
self.assertEqual(requests_seen, [])

def test_list_exports(self):
seen = self._expect_get("/v1/exports")
self.assertEqual(self.client.list_exports(), {})
self.assertEqual(len(seen), 1)

def test_get_export(self):
seen = self._expect_get("/v1/exports/110")
self.assertEqual(self.client.get_export(110), {})
self.assertEqual(len(seen), 1)

def test_download_export(self):
seen = self._expect_get("/v1/exports/110/download")
self.assertEqual(self.client.download_export("110"), {})
self.assertEqual(len(seen), 1)

def test_export_methods_require_ids(self):
requests_seen = []
self.client.http.hooks = dict(response=lambda resp, *a, **k: requests_seen.append(resp))
for export_id in (None, ""):
for method in (self.client.get_export, self.client.download_export):
with self.assertRaises(CustomerIOException):
method(export_id)
self.assertEqual(requests_seen, [])

def test_create_customers_export(self):
filters = {"and": [{"segment": {"id": 3}}]}
self.client.http.hooks = dict(
response=partial(
self._check_request,
rq={
"method": "POST",
"authorization": "Bearer app_api_key",
"content_type": "application/json",
"url_suffix": "/v1/exports/customers",
"body": {"filters": filters},
},
)
)
self.assertEqual(self.client.create_customers_export(filters), {})

self.client.http.hooks = dict(
response=partial(
self._check_request,
rq={
"method": "POST",
"authorization": "Bearer app_api_key",
"content_type": "application/json",
"url_suffix": "/v1/exports/customers",
"body": {"filters": filters, "attributes": ["email", "plan"]},
},
)
)
self.client.create_customers_export(filters, attributes=["email", "plan"])

def test_create_customers_export_requires_filters(self):
requests_seen = []
self.client.http.hooks = dict(response=lambda resp, *a, **k: requests_seen.append(resp))
for filters in (None, {}, [{"segment": {"id": 3}}]):
with self.assertRaises(CustomerIOException):
self.client.create_customers_export(filters)
self.assertEqual(requests_seen, [])

def test_create_deliveries_export(self):
self.client.http.hooks = dict(
response=partial(
self._check_request,
rq={
"method": "POST",
"authorization": "Bearer app_api_key",
"content_type": "application/json",
"url_suffix": "/v1/exports/deliveries",
"body": {"campaign_id": 46},
},
)
)
self.assertEqual(self.client.create_deliveries_export(campaign_id=46), {})

self.client.http.hooks = dict(
response=partial(
self._check_request,
rq={
"method": "POST",
"authorization": "Bearer app_api_key",
"content_type": "application/json",
"url_suffix": "/v1/exports/deliveries",
"body": {
"newsletter_id": 999,
"campaign_id": 46,
"action_id": 77,
"template_id": 5,
"transactional_message_id": 22,
"start": 1517529600,
"end": 1517702400,
"attributes": ["email"],
"metric": "delivered",
"drafts": False,
},
},
)
)
self.client.create_deliveries_export(
newsletter_id=999,
campaign_id=46,
action_id=77,
template_id=5,
transactional_message_id=22,
start=1517529600,
end=1517702400,
attributes=["email"],
metric="delivered",
drafts=False,
)

self.client.http.hooks = dict(
response=partial(
self._check_request,
rq={
"method": "POST",
"authorization": "Bearer app_api_key",
"content_type": "application/json",
"url_suffix": "/v1/exports/deliveries",
"body": {},
},
)
)
self.client.create_deliveries_export()

def test_create_deliveries_export_takes_keywords_only(self):
requests_seen = []
self.client.http.hooks = dict(response=lambda resp, *a, **k: requests_seen.append(resp))
with self.assertRaises(TypeError):
self.client.create_deliveries_export(999)
self.assertEqual(requests_seen, [])

def test_update_customer_optouts(self):
optouts = [
{"from": "+15551234567", "optout": True, "channel": "sms"},
Expand Down