Skip to main content

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 License: Proprietary


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

pip install trimlynk

Or using python -m pip:

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.


Quickstart

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

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

# 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

# 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

# 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

# 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

# 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():

# 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.

# 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:

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:

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


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.

Metadata

Release files for trimlynk 1.0.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for trimlynk 1.0.1
File Size Uploaded Provenance Actions
trimlynk-1.0.1.tar.gz 49.9 kB Without provenance Details for trimlynk-1.0.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for trimlynk 1.0.1
File Interpreter ABI Platform Actions
trimlynk-1.0.1-py3-none-any.whl Python 3 none any Details for trimlynk-1.0.1-py3-none-any.whl

Total release size: 95.9 kB

Release files / trimlynk-1.0.1.tar.gz

Download URL trimlynk-1.0.1.tar.gz
Size 49.9 kB
Tags Source
SHA-256 checksum
How to use checksums
22e0f32d2c2c6409c725f7fbbf49809b8d7e01d414b588092cfaa1ce71d57859
BLAKE2b-256 checksum
How to use checksums
7851ca70177cd627fb192b9d03f95eeb107bd4bc9181a07e89ac5bea6ebdd804
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / trimlynk-1.0.1-py3-none-any.whl

Download URL trimlynk-1.0.1-py3-none-any.whl
Size 46.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
ba1d532852f314a31123f1af9d629fbe2ffe00c0a3c2b3e7166466637de3eb9d
BLAKE2b-256 checksum
How to use checksums
55ff85b3029fe6eaa0f871f24c8900a64ba2b0100a278b210c37cc74ee0cd2b0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Security for trimlynk 1.0.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page