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
26 changes: 26 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -482,6 +482,32 @@ Only people who already exist get devices. Rows for unknown people are skipped,

With the one key `Client`, the same calls are on `cio.api_client`, for example `cio.api_client.create_import(...)`.

## Look up customers

The `APIClient` reads people and their data with an [app key](https://customer.io/docs/managing-credentials#app-api-keys). Each call returns the API's JSON as a dict.

```python
from customerio import APIClient, Regions

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

people = client.get_customers_by_email("jane@example.com")["results"]

found = client.search_customers({"and": [{"segment": {"id": 4}}]}, limit=100)
for person in found["identifiers"]:
print(person["cio_id"], person["id"], person["email"])

customer = client.get_customer_attributes("jane@example.com", id_type="email")["customer"]
profiles = client.get_customers_attributes(["1", "2"])["customers"]
```

* For one person: `get_customer_attributes`, `get_customer_activities`, `get_customer_messages`, `get_customer_relationships`, `get_customer_segments`, `get_customer_subscription_preferences` and `get_customer_optouts`.
* `id_type` says what kind of identifier you pass: `"id"`, `"email"`, `"phone"` or `"cio_id"`; without it, the value is read as an `id` (or a `cio_id`). `email` and `phone` work only when they are identifiers in your workspace. `get_customer_optouts` takes an `id` or `cio_id` only.
* Paged calls (`search_customers`, `get_customer_activities`, `get_customer_messages`, `get_customer_relationships`) return `next`; pass it back as `start` for the next page.
* `get_customers_attributes` takes up to 100 identifiers and leaves out people who don't exist.

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
144 changes: 144 additions & 0 deletions customerio/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -499,6 +499,150 @@ def _broadcast_action_language_url(self, broadcast_id, action_id, language):
language_segment = quote(str(language), safe="")
return f"{self._broadcast_action_url(broadcast_id, action_id)}/language/{language_segment}"

def get_customers_by_email(self, email):
"""Return the people in the workspace with this email address.

The response is ``{"results": [...]}``, one entry per person with their ``id``,
``email`` and ``cio_id``. The email is URL-encoded for you.
"""
if not isinstance(email, str) or email == "":
raise CustomerIOException("email is required")
url = self.url + "/v1/customers" + _query_string({"email": email})
resp = self.send_request("GET", url)
return resp.json()

def search_customers(self, filter, start=None, limit=None):
"""Return the people who match a filter, a page at a time.

``filter`` is a dict built from ``segment`` and ``attribute`` conditions,
combined with ``and``, ``or`` and ``not``, for example
``{"and": [{"segment": {"id": 4}}]}``. The response is
``{"identifiers": [...], "ids": [...], "next": "..."}``; prefer ``identifiers``,
since ``ids`` is an empty string for people without an ``id``. ``start`` is the
``next`` cursor from a previous page and ``limit`` is the page size (the API
defaults to 50 and allows up to 1000). Both are optional.
"""
if not isinstance(filter, dict) or not filter:
raise CustomerIOException("filter is required")
query = _query_string({"start": start, "limit": limit})
resp = self.send_request("POST", self.url + "/v1/customers" + query, {"filter": filter})
return resp.json()

def get_customers_attributes(self, ids, id_type=None):
"""Return the attributes and devices of up to 100 people in one request.

``ids`` is a list of identifiers, all of the kind ``id_type`` names (see
:meth:`get_customer_attributes`). The response is ``{"customers": [...]}``; people
who don't exist are left out.
"""
if not isinstance(ids, list) or not ids:
raise CustomerIOException("ids must be a non-empty list")
query = _query_string({"id_type": id_type})
url = self.url + "/v1/customers/attributes" + query
resp = self.send_request("POST", url, {"ids": self._stringify_list(ids)})
return resp.json()

def get_customer_attributes(self, customer_id, id_type=None):
"""Return a person's attributes, devices and identifiers (``{"customer": {...}}``).

``id_type`` says what kind of identifier ``customer_id`` is: ``"id"``,
``"email"``, ``"phone"`` or ``"cio_id"``. It is optional; without it the API
treats ``customer_id`` as an ``id`` (or a ``cio_id``). ``email`` and ``phone``
work only when they are enabled as identifiers in your workspace.
"""
query = _query_string({"id_type": id_type})
resp = self.send_request("GET", self._customer_url(customer_id) + "/attributes" + query)
return resp.json()

def get_customer_activities(
self, customer_id, id_type=None, start=None, limit=None, type=None, name=None
):
"""Return a person's activities, such as events, attribute changes and messages.

The response is ``{"activities": [...], "next": "..."}``. All filters are
optional: ``id_type`` works as in :meth:`get_customer_attributes`, ``start`` is
the ``next`` cursor from a previous page, ``limit`` is the page size (the API
defaults to 10 and allows up to 100), ``type`` is an activity type such as
``"event"`` or ``"attribute_change"``, and ``name`` is the event or attribute
name to match (the API accepts it only together with ``type``).
"""
query = _query_string(
{"id_type": id_type, "start": start, "limit": limit, "type": type, "name": name}
)
resp = self.send_request("GET", self._customer_url(customer_id) + "/activities" + query)
return resp.json()

def get_customer_messages(
self, customer_id, id_type=None, start=None, limit=None, start_ts=None, end_ts=None
):
"""Return the deliveries (messages) sent to a person.

The response is ``{"messages": [...], "next": "..."}``. All filters are
optional: ``id_type`` works as in :meth:`get_customer_attributes`, ``start`` is
the ``next`` cursor from a previous page, ``limit`` is the page size (the API
defaults to 50 and allows up to 1000), and ``start_ts`` and ``end_ts`` are Unix
timestamps.
"""
query = _query_string(
{
"id_type": id_type,
"start": start,
"limit": limit,
"start_ts": start_ts,
"end_ts": end_ts,
}
)
resp = self.send_request("GET", self._customer_url(customer_id) + "/messages" + query)
return resp.json()

def get_customer_relationships(self, customer_id, id_type=None, start=None, limit=None):
"""Return the objects a person is related to.

The response is ``{"cio_relationships": [...], "next": "..."}``. All filters are
optional: ``id_type`` works as in :meth:`get_customer_attributes`, ``start`` is
the ``next`` cursor from a previous page, and ``limit`` is the page size (the API
defaults to 50 and allows up to 1000).
"""
query = _query_string({"id_type": id_type, "start": start, "limit": limit})
url = self._customer_url(customer_id) + "/relationships" + query
resp = self.send_request("GET", url)
return resp.json()

def get_customer_segments(self, customer_id, id_type=None):
"""Return the segments a person belongs to (``{"segments": [...]}``).

``id_type`` works as in :meth:`get_customer_attributes`.
"""
query = _query_string({"id_type": id_type})
resp = self.send_request("GET", self._customer_url(customer_id) + "/segments" + query)
return resp.json()

def get_customer_subscription_preferences(self, customer_id, id_type=None, language=None):
"""Return a person's subscription preferences (``{"customer": {...}}``).

The response holds the person's topic choices plus the subscription center's
header, topic names and descriptions. ``id_type`` works as in
:meth:`get_customer_attributes`, and ``language`` is a language tag such as
``"fr"`` to translate the text into. Both are optional.
"""
query = _query_string({"id_type": id_type, "language": language})
url = self._customer_url(customer_id) + "/subscription_preferences" + query
resp = self.send_request("GET", url)
return resp.json()

def get_customer_optouts(self, customer_id):
"""Return the senders and channels a person has opted out of.

``customer_id`` is the person's ``id`` or ``cio_id``. The response is
``{"optouts": [{"from": ..., "channel": ...}, ...]}``; an entry means the person
is opted out of that sender on that channel (``"sms"`` or ``"whatsapp"``).
"""
resp = self.send_request("GET", self._customer_url(customer_id) + "/optouts")
return resp.json()

def _customer_url(self, customer_id):
return f"{self.url}/v1/customers/{_path_segment('customer_id', customer_id)}"

def _build_session(self):
session = super()._build_session()
session.headers["Authorization"] = f"Bearer {self.key}"
Expand Down
152 changes: 152 additions & 0 deletions tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -580,6 +580,158 @@ def test_broadcast_methods_require_ids(self):
with self.assertRaises(CustomerIOException):
self.client.update_broadcast_action_language(7, 21, "fr", None)

def test_get_customers_by_email(self):
seen = self._expect_get("/v1/customers?email=jane%2Bnews%40example.com")
self.assertEqual(self.client.get_customers_by_email("jane+news@example.com"), {})
self.assertEqual(len(seen), 1)

def test_search_customers(self):
search = {"and": [{"segment": {"id": 4}}]}
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/customers",
"body": {"filter": search},
},
)
)
self.assertEqual(self.client.search_customers(search), {})

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/customers?start=MDox&limit=100",
"body": {"filter": search},
},
)
)
self.client.search_customers(search, start="MDox", limit=100)

def test_get_customers_attributes(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/customers/attributes",
"body": {"ids": ["1", "2"]},
},
)
)
self.assertEqual(self.client.get_customers_attributes(["1", 2]), {})

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/customers/attributes?id_type=email",
"body": {"ids": ["jane@example.com"]},
},
)
)
self.client.get_customers_attributes(["jane@example.com"], id_type="email")

def test_get_customer_attributes(self):
seen = self._expect_get("/v1/customers/a%2Fb/attributes")
self.assertEqual(self.client.get_customer_attributes("a/b"), {})

self._expect_get("/v1/customers/jane%40example.com/attributes?id_type=email")
self.client.get_customer_attributes("jane@example.com", id_type="email")
self.assertEqual(len(seen), 1)

def test_get_customer_activities(self):
seen = self._expect_get("/v1/customers/5/activities")
self.assertEqual(self.client.get_customer_activities(5), {})

self._expect_get(
"/v1/customers/5/activities?id_type=cio_id&start=12&limit=20&type=event&name=purchase"
)
self.client.get_customer_activities(
5, id_type="cio_id", start="12", limit=20, type="event", name="purchase"
)
self.assertEqual(len(seen), 1)

def test_get_customer_messages(self):
seen = self._expect_get("/v1/customers/5/messages")
self.assertEqual(self.client.get_customer_messages(5), {})

self._expect_get(
"/v1/customers/5/messages?id_type=id&start=abc%3D&limit=10"
"&start_ts=1700000000&end_ts=1700086400"
)
self.client.get_customer_messages(
5, id_type="id", start="abc=", limit=10, start_ts=1700000000, end_ts=1700086400
)
self.assertEqual(len(seen), 1)

def test_get_customer_relationships(self):
seen = self._expect_get("/v1/customers/5/relationships")
self.assertEqual(self.client.get_customer_relationships(5), {})

self._expect_get("/v1/customers/5/relationships?id_type=email&start=MToy&limit=5")
self.client.get_customer_relationships(5, id_type="email", start="MToy", limit=5)
self.assertEqual(len(seen), 1)

def test_get_customer_segments(self):
seen = self._expect_get("/v1/customers/5/segments")
self.assertEqual(self.client.get_customer_segments(5), {})

self._expect_get("/v1/customers/5/segments?id_type=cio_id")
self.client.get_customer_segments(5, id_type="cio_id")
self.assertEqual(len(seen), 1)

def test_get_customer_subscription_preferences(self):
seen = self._expect_get("/v1/customers/5/subscription_preferences")
self.assertEqual(self.client.get_customer_subscription_preferences(5), {})

self._expect_get("/v1/customers/5/subscription_preferences?id_type=id&language=pt-BR")
self.client.get_customer_subscription_preferences(5, id_type="id", language="pt-BR")
self.assertEqual(len(seen), 1)

def test_get_customer_optouts(self):
seen = self._expect_get("/v1/customers/5/optouts")
self.assertEqual(self.client.get_customer_optouts(5), {})
self.assertEqual(len(seen), 1)

def test_customer_methods_require_ids(self):
for customer_id in (None, ""):
for method in (
self.client.get_customer_attributes,
self.client.get_customer_activities,
self.client.get_customer_messages,
self.client.get_customer_relationships,
self.client.get_customer_segments,
self.client.get_customer_subscription_preferences,
self.client.get_customer_optouts,
):
with self.assertRaises(CustomerIOException):
method(customer_id)

for email in (None, ""):
with self.assertRaises(CustomerIOException):
self.client.get_customers_by_email(email)
for search in (None, {}, "segment"):
with self.assertRaises(CustomerIOException):
self.client.search_customers(search)
for ids in (None, [], "1"):
with self.assertRaises(CustomerIOException):
self.client.get_customers_attributes(ids)
with self.assertRaises(CustomerIOException):
self.client.get_customers_attributes([{"id": "1"}])


if __name__ == "__main__":
unittest.main()