# Python

Synchronous and asynchronous server clients for sessions, payments, invoices, balances, Customer messaging and Funnel decisions.

Last updated: 2026-11-06

[Web version](https://www.longplayai.com/docs/sdk/python)

<a id="install"></a>

## Install

**terminal**

```bash
SDK_VERSION="$(curl -fsS 'https://cdn.longplayai.com/sdk/longplay/stable?package=python')" &&
python -m pip install "https://cdn.longplayai.com/downloads/python/tinkerlandai_longplay_sdk-$SDK_VERSION-py3-none-any.whl" &&
python -m pip freeze > requirements.lock
```

Resolve the latest stable release, then freeze exact dependencies in requirements.lock. Python 3.11+. Distributed from longplayai.com rather than PyPI; the distribution is `tinkerlandai-longplay-sdk` and the import is `longplay`.

- [pip, uv and requirements.txt](https://www.longplayai.com/docs/install.md#python)

<a id="sync"></a>

## Synchronous client

Set `LONGPLAY_SERVER_KEY`, `LONGPLAY_PROJECT_ID` and `LONGPLAY_API_URL` (https://api.longplayai.com here). Events and Features must already be configured in that App's Sandbox.

**usage.py**

```python
import os

from longplay import Longplay

with Longplay(
    api_key=os.environ["LONGPLAY_SERVER_KEY"],
    project_id=os.environ["LONGPLAY_PROJECT_ID"],
    environment="sandbox",
    base_url=os.environ["LONGPLAY_API_URL"],
) as client:
    result = client.get_or_create_customer(external_user_id="merchant-user-123")
    customer_id = result["customer"]["id"]

    holdings = client.read_holdings(customer_id=customer_id)
    check = client.check_entitlement(
        customer_id=customer_id,
        internal_feature_id=os.environ["LONGPLAY_FEATURE_ID"],
        quantity="1",
    )
    if check["check"]["allowed"]:
        usage = client.track_usage(
            customer_id=customer_id,
            event_name="image_generated",
            quantity="1.25",
            properties={"quality": "hd"},
            idempotency_key="merchant-event-123",
        )
        for receipt in usage["receipts"]:
            print(receipt["accepted"], receipt.get("reason"))
```

An entitlement check only observes access; usage is a separate write. HTTP success does not mean a debit was accepted: inspect each receipt's `accepted` and `reason`.

<a id="async"></a>

## Asynchronous client

**holdings.py**

```python
import os

from longplay import AsyncLongplay


async def read_customer_holdings(external_user_id: str):
    async with AsyncLongplay(
        api_key=os.environ["LONGPLAY_SERVER_KEY"],
        project_id=os.environ["LONGPLAY_PROJECT_ID"],
        environment="sandbox",
        base_url=os.environ["LONGPLAY_API_URL"],
    ) as client:
        result = await client.get_or_create_customer(external_user_id=external_user_id)
        return await client.read_holdings(customer_id=result["customer"]["id"])
```

Reuse one client in a long-running service and close it on shutdown with `close()` (sync) or `await aclose()` (async). Both accept `timeout` in seconds (default 10, maximum 120) and an HTTPX `transport=` for tests or custom networking. Ambient proxies and cookies are not used and redirects are not followed.

<a id="methods"></a>

## Methods

**All arguments are keyword-only; returned TypedDicts keep wire keys such as `customerId`.**

| Method | Inputs and behavior | Scope |
| --- | --- | --- |
| `get_or_create_customer` | `external_user_id` or `email`; optional `name`, `attributes`, `fingerprint`. Existing records are not patched. | `customers:write` |
| `get_customer` | Exactly one of `customer_id` or `external_user_id`. | `customers:read` |
| `list_customers` | Filters with explicit `offset`/`limit`; returns `customers`, `hasMore`, `total`. | `customers:read` |
| `update_customer` | A retained `request_id`, one lookup and a partial patch: `name`, `email`, `attributes`, `remove_attributes`, `add_tags`, `remove_tags`. | `customers:write` |
| `read_holdings` | `customer_id`, optional `entity_id`. | `entitlements:read` |
| `check_entitlement` | `customer_id`, `internal_feature_id`; positive decimal-string `quantity`, optional `properties`/`entity_id`. | `entitlements:read` |
| `track_usage` | `customer_id`, a retained `idempotency_key`, exactly one of `event_name` or `internal_feature_id`; decimal-string `quantity`, optional `properties`/`entity_id`. | `credits:consume` |
| `send_message` | A retained `request_id`, `customer_id`, channel-tagged `message`, `expires_at` and optional `connection_id`. | `messaging:write` |
| `read_message` | `message_id`; read dispatch state and verified receipts. | `messaging:write` |

Omitted fields stay omitted; `None` is not an alias for omission. Quantities are decimal strings, never floats. Import the generated TypedDicts from `longplay.models`.

<a id="errors"></a>

## Errors and recovery

**errors.py**

```python
from longplay import LongplayError

try:
    holdings = client.read_holdings(customer_id=customer_id)
except LongplayError as error:
    print(error.code, error.status, error.request_id, error.retryable, error.recovery)
```

`LongplayError` exposes `code`, `status`, `request_id`, `retryable`, `recovery`, and optional `reason` and `retry_after_seconds`; it never retains the Key or payload. There are no automatic retries: persist the `idempotency_key` or `request_id` before sending and replay the same value and input after an uncertain result. `TIMEOUT`, `NETWORK_ERROR` and cancellation do not mean rollback.

<a id="other-operations"></a>

## Sessions and full coverage

The Python SDK provides methods for current Server-Key/mixed-credential operations, including sessions, payments, offers, invoices, balance management and Customer messaging. Reserved operations still return 501; check reference pages for other unsupported branches. Use the SDK's Funnel client for Funnel decisions. See available methods below and the full support matrix, which also includes reserved entries.

**Methods by area**

| Area | Methods |
| --- | --- |
| Customer messaging and installations | `send_message`, `read_message` |
| Customers, Guests and Sessions | `get_or_create_customer`, `get_customer`, `list_customers`, `update_customer`, `create_session`, `revoke_sessions`, `create_guest_customer`, `resume_guest_session`, `claim_guest_customer` |
| Entitlements and product presentation | `check_entitlement`, `resolve_offering`, `resolve_paywall`, `read_holdings` |
| Balances, usage and ledger | `read_balance_source`, `adjust_balance`, `read_usage`, `set_usage`, `manage_balance_grant`, `list_balance_grants`, `manage_usage_entity`, `read_usage_analytics`, `read_credit_analytics`, `submit_usage_batch`, `read_usage_batch`, `read_ledger`, `read_credit_statement`, `quote_balance`, `track_usage`, `mutate_balance` |
| Seats | `read_seats`, `manage_seat` |
| Subscriptions and payments | `setup_payment`, `read_payment_setup`, `verify_subscriptions`, `preview_attach`, `attach`, `read_subscription_operation`, `preview_update`, `update`, `read_subscription_update`, `list_subscriptions`, `list_purchases`, `list_subscription_conflicts`, `retry_subscription_conflict`, `manage_subscription_trial`, `read_subscription_trial`, `preview_subscription_batch`, `confirm_subscription_batch`, `read_subscription_batch`, `abandon_subscription_batch`, `record_merchant_event` |
| Invoices, refunds and billing | `list_invoice_templates`, `preview_invoice`, `create_invoice`, `manage_invoice`, `read_invoice_operation`, `list_invoices`, `get_invoice`, `preview_refund`, `refund`, `read_refund`, `manage_billing_limits`, `read_billing_invoice`, `prepare_billing_adjustment` |
| Coupons, rewards and referrals | `grant_offer`, `grant_model_benefit`, `read_model_benefit` |
| Feature flags, evaluation and events | `get_features`, `evaluate_features`, `track_events` |
| Native purchases | `restore_native_purchase` |
| AI pricing | `read_ai_pricing` |
| CLI and CI | `resolve_content`, `get_code_reference_config`, `submit_code_references` |

After authenticating the user and resolving their Customer on your backend, issue the session with a Server Key holding `sessions:create`. Return the complete session, including `customerId`, `sessionId`, `accessToken`, `refreshToken`, `expiresAt` and `refreshExpiresAt`, to that user's frontend and pass it to `identify(session)`; the frontend SDK handles subsequent refreshes.

**sessions.py**

```python
from longplay import Longplay
from longplay.models import CreateSessionResponse


def issue_customer_session(client: Longplay, customer_id: str) -> CreateSessionResponse:
    # Resolve customer_id from your authenticated user on the backend.
    # Return the complete session to the same user's browser or app.
    return client.create_session(request={"customerId": customer_id})
```

- [Support matrix](https://www.longplayai.com/docs/guides/platforms.md)
- [All operations](https://www.longplayai.com/docs/api/operations.md)
- [Request conventions](https://www.longplayai.com/docs/api.md)
