Metadata-Version: 2.4
Name: trimlynk
Version: 1.0.1
Summary: Official Python SDK for the TrimLynk Developer API v1
Author: Vivek Gaur, Ashish Kumar Dwivedi, TrimLynk
Author-email: support@trimlynk.com
Maintainer: Vivek Gaur, Ashish Kumar Dwivedi
Maintainer-email: support@trimlynk.com
License-Expression: LicenseRef-Proprietary
Project-URL: Homepage, https://trimlynk.com
Project-URL: Documentation, https://trimlynk.com/developers/sdks
Project-URL: API Reference, https://trimlynk.com/api-docs
Project-URL: Support, https://trimlynk.com/contact
Project-URL: Terms of Service, https://trimlynk.com/terms
Keywords: trimlynk,url-shortener,link-management,analytics,webhooks,attribution,developer-api
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Topic :: Internet :: WWW/HTTP
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: dev
Requires-Dist: pytest>=8.4.0; extra == "dev"
Requires-Dist: pytest-cov>=5.0.0; extra == "dev"
Requires-Dist: pip-audit>=2.8.0; extra == "dev"
Provides-Extra: keyring
Requires-Dist: keyring>=25.0.0; extra == "keyring"
Dynamic: license-file

# TrimLynk Official Python SDK

The official Python client library for the **TrimLynk Developer API v1**.

TrimLynk is a modern, privacy-first URL shortening, link intelligence, and attribution platform. This SDK provides programmatic access to link creation, analytics telemetry, conversion funnel tracking, marketing campaigns, and real-time webhook management.

[![Python Version](https://img.shields.io/badge/python-3.9+-blue.svg)](https://python.org)
[![License: Proprietary](https://img.shields.io/badge/license-Proprietary-red.svg)](https://trimlynk.com/terms)

---

## Features

* **Zero External Dependencies**: Implemented using the Python standard library. No bloated dependency trees or version conflicts.
* **Production-Grade Idempotency**: Safe mutations with `idempotency_key` on link, campaign, and webhook operations.
* **Complete Resource Coverage**: Links, Workspace Analytics, Link Telemetry, Conversion Funnels, Marketing Campaigns, and Webhook Subscriptions.
* **Automatic Paging**: Stream effortlessly through thousands of records using `resource.iter()` without manual pagination logic.
* **Strong Type Hints**: Full type annotations and dataclass models throughout for IDE autocompletion and safety.
* **Transparent Request Tracing**: Access `request_id` directly on every returned model and caught exception.
* **Structured Error Taxonomy**: Typed exceptions mapping cleanly to HTTP 400, 401, 403, 404, 409, 429, and 500 status codes.
* **Strict Security**: API keys, credentials, and Authorization headers are masked and never exposed in logs or exception messages.
* **Official CLI Included**: Installs the production-ready `trimlynk` command-line interface.

---

## Installation

```bash
pip install trimlynk
```

Or using `python -m pip`:

```bash
python -m pip install trimlynk
```

Installing the package exposes both the Python client library and the `trimlynk` command-line executable. For complete CLI documentation, see [CLI Reference](https://trimlynk.com/developers/sdks).

---

## Quickstart

```python
from trimlynk import TrimLynk

# 1. Initialize with an API key
client = TrimLynk(api_key="tl_live_your_api_key_here")

# 2. Or initialize from the TRIMLYNK_API_KEY environment variable
# client = TrimLynk()

# 3. Create a shortened link
link = client.links.create(
    original_url="https://example.com/summer-launch?sku=123",
    custom_slug="summer-launch-2026",
    title="Summer Launch 2026",
    tags=["promo", "summer"],
    utm_source="newsletter",
    utm_medium="email",
    utm_campaign="summer_2026",
)

print(f"Short URL: {link.short_url}")
print(f"Request ID: {link.request_id}")
```

---

## Client Configuration

```python
client = TrimLynk(
    api_key="tl_live_xxx",             # Or set via TRIMLYNK_API_KEY
    base_url="https://api.trimlynk.com", # Optional custom endpoint
    environment="live",                 # "live" or "test"
    timeout=30.0,                       # Network timeout in seconds (default: 30)
)
```

---

## Resources & Examples

### 1. Links

```python
# Create a link
link = client.links.create(
    original_url="https://example.com",
    title="Homepage",
    idempotency_key="unique-op-key-001",
)

# Retrieve a single link
link = client.links.get(link.id)

# Update a link
updated = client.links.update(
    link.id,
    title="Updated Title",
    is_active=True,
)

# List links with filtering and sorting
page = client.links.list(page=1, limit=50, tag="promo", sort="latest")
for l in page:
    print(l.short_url, l.clicks)

# Delete a link
client.links.delete(link.id)
```

### 2. Analytics

```python
# Workspace aggregate metrics
analytics = client.analytics.get(
    start_date="2026-09-01T00:00:00Z",
    end_date="2026-09-24T00:00:00Z",
)
print("Total clicks:", analytics.total_clicks)
print("Top devices:", analytics.devices)
print("Top countries:", analytics.countries)

# Link-specific telemetry
link_stats = client.analytics.get_link("clk_link_id")
print("Clicks for link:", link_stats.clicks)

# Conversion funnel metrics (Click -> Lead -> Sale)
funnel = client.analytics.conversions(url_id="clk_link_id")
print("Attributed revenue:", funnel.revenue)
print("Funnel steps:", funnel.metrics)
```

### 3. Conversions

```python
# Ingest an e-commerce or lead conversion event
conv = client.conversions.create(
    url_id="clk_link_id",
    event_name="purchase",
    event_value=79.99,
    currency="USD",
    customer_id="cust_9876",
    order_id="ord_12345",
    metadata={"plan": "pro"},
)

# List recent conversions
history = client.conversions.list(page=1, limit=20, event_name="purchase")
for event in history:
    print(event.event_name, event.event_value, event.created_at)
```

### 4. Campaigns

```python
# Create a marketing campaign with idempotency
campaign = client.campaigns.create(
    name="Q4 Growth",
    description="Q4 Marketing acquisition drive",
    utm_source="google",
    utm_medium="cpc",
    utm_campaign="q4_growth",
    idempotency_key="camp-q4-growth-01",
)

# List campaigns
campaigns = client.campaigns.list(page=1, limit=50)

# Update campaign
client.campaigns.update(campaign.id, description="Updated Q4 strategy")

# Delete campaign
client.campaigns.delete(campaign.id)
```

### 5. Webhooks

```python
# Register a webhook endpoint
hook = client.webhooks.create(
    url="https://api.example.com/trimlynk/webhooks",
    events=["link.created", "link.updated", "click.created", "conversion.created"],
    description="Primary production webhook",
    idempotency_key="whk-setup-01",
)

# NOTE: The signing secret is revealed once upon creation
print("Webhook signing secret:", hook.secret)

# Dispatch a test ping
test_result = client.webhooks.test(hook.id)
print("Ping status:", test_result.success)

# Inspect delivery logs
deliveries = client.webhooks.deliveries(hook.id, page=1, limit=10)
for attempt in deliveries:
    print(attempt.event, attempt.status_code, attempt.duration_ms)

# Manually retry a failed delivery
client.webhooks.retry(hook.id, deliveries[0].id)
```

---

## Automatic Pagination

All list resources support convenient auto-paging via `.iter()`:

```python
# Seamlessly streams across all pages (max 100 items per batch)
for link in client.links.iter(limit=100, tag="summer"):
    print(link.short_url)

for conversion in client.conversions.iter():
    print(conversion.event_name, conversion.event_value)

for webhook in client.webhooks.iter():
    print(webhook.url)
```

---

## Idempotency

Mutating endpoints (`POST /links`, `POST /campaigns`, `POST /webhooks`) accept an optional `idempotency_key`.

```python
# Sending the initial request
link = client.links.create(
    original_url="https://example.com/checkout",
    idempotency_key="order_98124_link",
)
print("Replayed:", link.idempotent_replay)  # None or False

# Retrying with the identical key returns the cached response
replayed = client.links.create(
    original_url="https://example.com/checkout",
    idempotency_key="order_98124_link",
)
print("Replayed:", replayed.idempotent_replay)  # True
assert link.id == replayed.id
```

If an existing key is reused with a different request body, the SDK raises `IdempotencyConflictError` (HTTP 409).

---

## Error Handling

The SDK maps all HTTP and network errors into a clean, typed hierarchy:

```text
TrimLynkError
├── APIError
│   ├── InvalidRequestError       (HTTP 400)
│   ├── AuthenticationError       (HTTP 401)
│   ├── PermissionError           (HTTP 403)
│   ├── NotFoundError             (HTTP 404)
│   ├── ConflictError             (HTTP 409)
│   │   └── IdempotencyConflictError
│   ├── RateLimitError            (HTTP 429)
│   └── InternalServerError       (HTTP 500)
├── NetworkError
└── TimeoutError
```

### Example:

```python
from trimlynk import (
    TrimLynk,
    InvalidRequestError,
    AuthenticationError,
    RateLimitError,
    IdempotencyConflictError,
    TrimLynkError,
)

client = TrimLynk()

try:
    client.links.create(original_url="https://example.com")

except InvalidRequestError as e:
    print(f"Validation error ({e.code}): {e.message}")
    print("Field violation:", e.details)
    print("Request ID:", e.request_id)

except RateLimitError as e:
    print(f"Rate limited: retry after {e.retry_after} seconds")
    print("Request ID:", e.request_id)

except IdempotencyConflictError as e:
    print(f"Idempotency key collision: {e.message}")

except AuthenticationError as e:
    print("Invalid or revoked API key.")

except TrimLynkError as e:
    print(f"General error: {e}")
```

---

## Security

* **HTTPS Enforcement**: Default connection uses TLS (`https://api.trimlynk.com`).
* **Secret Protection**: API keys and Authorization headers are masked in `repr()` and omitted from all serialized dictionaries and error messages.
* **Zero Dependency Risk**: Built exclusively on standard Python modules to guarantee supply chain integrity.

---

## Authors & Maintainers

* **TrimLynk Team** — [support@trimlynk.com](mailto:support@trimlynk.com)
* **Vivek Gaur** — [ankygaur9972@gmail.com](mailto:ankygaur9972@gmail.com)
* **Ashish Kumar Dwivedi** — [adpassward709@gmail.com](mailto:adpassward709@gmail.com)

---

## License

Proprietary License (All Rights Reserved). Licensed under the TrimLynk Software License Agreement. For complete terms of service and acceptable use policies, please visit [TrimLynk Terms of Service](https://trimlynk.com/terms).
