TrimLynk — Official Python SDK & CLI
Official Python client library and CLI for the TrimLynk Developer API v1.
TrimLynk is a modern, privacy-first URL shortening, link intelligence, and conversion attribution SaaS platform. This SDK enables developers to programmatically create short links, measure visitor telemetry, attribute multi-touch conversion funnels, orchestrate marketing campaigns, export QR codes, and receive real-time webhook events with zero required runtime dependencies.
Official Resources & Navigation
Platform Dashboard · Developer Hub · SDK Documentation · API Reference · Webhooks Guide · PyPI Package · Support
What Can You Build with TrimLynk?
- Programmatic Branded Short Links: Generate branded short links on-the-fly for user invitations, SMS notifications, transactional emails, and receipts.
- Audience Telemetry & Click Analytics: Query aggregate workspace and link-level click telemetry, including devices, countries, referrers, and browsers.
- Conversion Funnels & Revenue Attribution: Track full-funnel customer journeys (Click $\to$ Lead $\to$ Sale) with attributed revenue, currency, order IDs, and click attribution.
- Marketing Campaign Orchestration: Group links into campaign folders with automated UTM tag injection (
auto_decorate_utm=True) and progress tracking against click goals. - QR Code Generation & Export: Generate and save decoded PNG, SVG, or raw image QR codes directly to disk with a single call.
- Real-Time Webhook Pipelines: Ingest platform events with 1-line HMAC-SHA256 signature verification and typed event models.
- High-Throughput Concurrent Batches: Create links in bulk using thread-pooled (
max_workers) or asynchronous (concurrency) bounded batches. - Developer CLI with Webhook Tunneling: Manage links from your terminal and forward live webhook events to local web servers (
localhost:8000) without public IP configuration.
Installation
# Standard zero-dependency installation
pip install trimlynk
The core SDK requires Python 3.9+ and has zero third-party runtime dependencies.
Optional Integrations
# With secure system credential store support for the CLI (macOS Keychain, Windows Credential Manager, Secret Service)
pip install "trimlynk[keyring]"
# With Pandas DataFrame export support for analytics and data science pipelines
pip install "trimlynk[data]"
Installing the package automatically provides both the trimlynk Python SDK and the trimlynk command-line executable.
30-Second Quickstart
from trimlynk import TrimLynk
# 1. Initialize client (reads TRIMLYNK_API_KEY environment variable if omitted)
client = TrimLynk()
# 2. Create a shortened link
link = client.links.create(
original_url="https://example.com/products/wireless-headphones"
)
print(f"Short URL: {link.short_url}")
print(f"Link ID: {link.id}")
Authentication & Configuration
Authenticate by providing an API key generated in your TrimLynk workspace settings (Settings > API Keys).
Recommended: Environment Variable
Set TRIMLYNK_API_KEY in your environment or .env file:
export TRIMLYNK_API_KEY="tl_live_abcdef1234567890abcdef1234567890"
Initialize without arguments:
from trimlynk import TrimLynk
client = TrimLynk()
Explicit Client Configuration
from trimlynk import TrimLynk
client = TrimLynk(
api_key="tl_live_abcdef1234567890abcdef1234567890",
environment="live", # "live" for production, "test" for test-key validation
timeout=30.0, # Network timeout in seconds (default: 30.0)
base_url="https://api.trimlynk.com", # Optional API root override
)
API Key Formats
- Production Environment:
tl_live_<entropy>(Default for live traffic and production workloads) - Test Keys:
tl_test_<entropy>(For test workspaces, CI pipelines, and automated test suites)
Credential Resolution Precedence
When initializing a client or executing CLI commands, credentials resolve in the following order:
- Explicit client argument (
TrimLynk(api_key="...")or CLI--api-key) - Environment variable (
TRIMLYNK_API_KEY) - OS Credential Manager / Keyring (
trimlynk[keyring]) - Local credentials file (
~/.trimlynk/credentials.json)
Synchronous and Asynchronous Usage
The SDK provides both synchronous (TrimLynk) and asynchronous (AsyncTrimLynk) clients sharing identical resource models.
Synchronous Client (TrimLynk)
Ideal for standard scripts, Django, Flask, Celery, and synchronous workers:
from trimlynk import TrimLynk
with TrimLynk() as client:
link = client.links.create(
original_url="https://example.com/promo",
slug="spring-promo",
)
print("Created:", link.short_url)
Asynchronous Client (AsyncTrimLynk)
Designed specifically for FastAPI, Aiohttp, asyncio background workers, and real-time streaming bots:
import asyncio
from trimlynk import AsyncTrimLynk
async def main():
async with AsyncTrimLynk() as client:
# Create a single link asynchronously
link = await client.links.create(
original_url="https://example.com/promo",
slug="async-promo",
)
print("Created:", link.short_url)
# Batch create with bounded concurrency
links = await client.links.create_many(
[
{"original_url": "https://example.com/1", "slug": "async-item-1"},
{"original_url": "https://example.com/2", "slug": "async-item-2"},
],
concurrency=5,
)
# Stream through all links with non-blocking auto-pagination
async for item in client.links.iter(limit=50):
print(item.short_code, item.clicks)
asyncio.run(main())
SDK Architecture & Resource Model
TrimLynk / AsyncTrimLynk
├── links # Shortened URLs, custom slugs, tags, QR code exports, batch creation
├── analytics # Workspace aggregations, per-link metrics, conversion funnels
├── conversions # Customer conversion tracking, revenue attribution, order IDs
├── campaigns # Marketing campaign folders, click goals, budgets, UTM tracking
└── webhooks # Endpoint registrations, delivery attempt logs, retries, HMAC verification
Core Capabilities
1. Links Management
Create, retrieve, update, and delete shortened links:
from trimlynk import TrimLynk
client = TrimLynk()
# Create a link with slug, tags, title, and UTM parameters
link = client.links.create(
original_url="https://example.com/deals/summer",
slug="summer-deals",
title="Summer 2026 Promotional Campaign",
tags=["marketing", "summer"],
utm_source="newsletter",
utm_medium="email",
utm_campaign="summer_launch",
auto_decorate_utm=True, # Appends UTM parameters to destination URL
idempotency_key="create_summer_001",# Prevents accidental duplicate creations
)
print(f"Short URL: {link.short_url}")
print(f"QR Code: {link.qr_code}")
# Retrieve link details
fetched = client.links.get("summer-deals")
print(f"Clicks: {fetched.clicks}")
# Update link destination or tags
updated = client.links.update(
"summer-deals",
original_url="https://example.com/deals/summer-v2",
title="Summer Deals V2",
is_active=True,
)
# Concurrent batch creation (sync uses max_workers, async uses concurrency)
batch = client.links.create_many([
{"original_url": "https://example.com/a", "slug": "link-a"},
{"original_url": "https://example.com/b", "slug": "link-b"},
], max_workers=4)
# Delete link
client.links.delete("summer-deals")
2. QR Code Generation & File Export
Every TrimLynk link can generate an accompanying QR code. Decode and save Base64 PNG, SVG markup, or remote images directly to a local file:
# Option 1: Save directly from Link model
link = client.links.get("url_abc123")
saved_path = link.save_qr("assets/deal_qr.png")
# Option 2: Fetch and save in a single call via links resource
client.links.download_qr("url_abc123", "assets/deal_qr.png")
# Async equivalent
await async_client.links.download_qr("url_abc123", "assets/deal_qr.png")
3. Click Analytics & Audience Telemetry
Inspect workspace aggregate metrics, individual link breakdowns, and conversion funnels:
from datetime import date
# 1. Workspace aggregate summary (accepts ISO strings, date, or datetime)
summary = client.analytics.get(
start_date=date(2026, 1, 1),
end_date=date(2026, 1, 31),
)
print(f"Total Clicks: {summary.total_clicks:,}")
print(f"Unique Visitors: {summary.unique_visitors:,}")
print("Top Devices: ", summary.devices)
print("Top Countries: ", summary.countries)
print("Top Referrers: ", summary.referrers)
# 2. Detailed click breakdown for a specific link
link_stats = client.analytics.get_link("url_abc123")
print(f"Link Clicks: {link_stats.clicks}")
# 3. Conversion funnel metrics (Click -> Lead -> Sale)
funnel = client.analytics.conversions(link_id="url_abc123")
print(f"Attributed Revenue: ${funnel.revenue:.2f}")
print("Funnel Metrics: ", funnel.metrics)
4. Conversions & Revenue Attribution Tracking
Attribute downstream business outcomes (signups, leads, purchases) to short links and click IDs:
# Record an attributed purchase event
conversion = client.conversions.create(
link_id="url_abc123",
event_name="checkout_completed",
revenue=149.50,
currency="USD",
order_id="ord_99812",
customer_email="buyer@example.com",
click_id="clk_554433", # Links conversion to a specific click session
idempotency_key="order_99812_conv", # Business deduplication
)
print(f"Recorded conversion {conversion.id} for order #{conversion.order_id}")
# List recorded conversions for a link
conversions_page = client.conversions.list(
link_id="url_abc123",
event_name="checkout_completed",
limit=25,
)
for c in conversions_page:
print(c.event_name, c.revenue, c.currency, c.created_at)
5. Marketing Campaigns
Organize links under strategic campaign folders and track progress against target click goals:
# Create a marketing campaign
campaign = client.campaigns.create(
name="Q3 Growth Blitz",
description="Multi-channel promotional outreach",
goal=10000, # Target click goal
status="active",
utm_source="newsletter",
utm_medium="email",
utm_campaign="q3_blitz",
)
print(f"Campaign ID: {campaign.id}, Goal: {campaign.goal}")
# List campaigns in workspace
campaigns = client.campaigns.list()
for camp in campaigns:
print(camp.name, camp.status, camp.link_count)
Webhooks Ingestion & Verification
TrimLynk webhooks notify your backend in real-time when links are clicked, updated, or when customer conversions are recorded.
Canonical Platform Event Types
| Event Name | Description |
|---|---|
click.created |
Visitor click registered and telemetry processed |
conversion.created |
Generic customer conversion recorded |
lead.created |
Lead-stage conversion event attributed |
sale.created |
Completed checkout / purchase event attributed |
link.created |
Shortened link registered |
link.updated |
Link destination, slug, or metadata updated |
link.deleted |
Shortened link deleted |
Registering Webhooks
webhook = client.webhooks.create(
url="https://api.yourdomain.com/webhooks/trimlynk",
events=["click.created", "conversion.created", "sale.created"],
description="Production event ingestion endpoint",
)
# Store the signing secret securely; it is displayed only once
print("Webhook ID:", webhook.id)
print("Signing Secret:", webhook.secret)
Ingestion & Verification (FastAPI Example)
Verify incoming X-TrimLynk-Signature headers using HMAC-SHA256 and deserialize payloads into typed WebhookEvent instances:
from fastapi import FastAPI, Request, HTTPException
from trimlynk import TrimLynk, SignatureVerificationError
app = FastAPI()
client = TrimLynk()
@app.post("/webhooks/trimlynk")
async def handle_trimlynk_webhook(request: Request):
raw_payload = await request.body()
signature_header = request.headers.get("x-trimlynk-signature")
try:
# 1-step cryptographic verification and typed parsing
event = client.webhooks.construct_event(
raw_payload=raw_payload,
signature_header=signature_header,
secret="whsec_your_webhook_signing_secret",
tolerance_seconds=300, # Reject replay attacks older than 5 minutes
)
except SignatureVerificationError as err:
raise HTTPException(status_code=400, detail=str(err))
# Inspect event using typed property accessors
if event.is_click:
print(f"Click on {event.short_url} via {event.channel}")
elif event.is_conversion:
print(f"Attributed {event.event_name} on order #{event.order_id}: ${event.revenue}")
return {"status": "success"}
Delivery Logs & Retries
# Inspect recent delivery attempts
deliveries = client.webhooks.deliveries("whk_123", limit=20)
for delivery in deliveries:
print(delivery.id, delivery.event, delivery.status_code, delivery.duration_ms)
# Manually trigger a retry of a failed delivery
client.webhooks.retry("whk_123", "del_456")
Production Features
Idempotent Mutations
Mutating calls (client.links.create, client.conversions.create, client.campaigns.create, client.webhooks.create) accept an optional idempotency_key argument. Replaying a request with the same idempotency key returns the original result safely without creating duplicates:
link = client.links.create(
original_url="https://example.com/order-confirmation",
idempotency_key="order_ack_99182",
)
print(link.idempotent_replay) # True on replayed requests
Automatic Pagination
Transparently iterate across multi-page collections without manual page cursor handling:
# Synchronous auto-pagination
for link in client.links.iter(limit=100, tag="promo"):
print(link.short_url, link.clicks)
# Asynchronous auto-pagination
async for webhook in async_client.webhooks.iter(limit=50):
print(webhook.url, webhook.events)
Supported on client.links.iter(), client.conversions.iter(), client.campaigns.iter(), client.webhooks.iter(), and client.webhooks.iter_deliveries(webhook_id).
Typed Models & Envelopes
Every resource method returns strongly-typed Python @dataclass models (Link, AnalyticsSummary, LinkAnalytics, FunnelAnalytics, Campaign, Conversion, Webhook, WebhookDelivery). Every model exposes a .to_dict() helper for serialization and a request_id attribute for correlated logging.
Forgiving Parameter Aliases
The SDK normalizes common parameter conventions:
slug$\leftrightarrow$custom_slug$\leftrightarrow$custom_urllink_id$\leftrightarrow$url_idrevenue$\leftrightarrow$event_value$\leftrightarrow$value$\leftrightarrow$amount- Native Python
datetime.dateanddatetime.datetimeobjects are automatically serialized to ISO-8601 strings.
Error Handling
All HTTP and network failures map into a structured exception hierarchy:
TrimLynkError
├── NetworkError
│ └── TimeoutError
├── APIError (status_code, code, request_id, details)
│ ├── InvalidRequestError (HTTP 400)
│ ├── AuthenticationError (HTTP 401)
│ ├── PermissionError (HTTP 403)
│ ├── NotFoundError (HTTP 404)
│ ├── ConflictError (HTTP 409)
│ │ └── IdempotencyConflictError
│ ├── RateLimitError (HTTP 429: retry_after)
│ └── InternalServerError (HTTP 500)
└── SignatureVerificationError
├── SignatureExpiredError
├── SignatureMismatchError
└── InvalidSignatureHeaderError
Recommended Error Handling Pattern
from trimlynk import TrimLynk
from trimlynk.exceptions import (
APIError,
AuthenticationError,
ConflictError,
IdempotencyConflictError,
InvalidRequestError,
NetworkError,
NotFoundError,
RateLimitError,
TimeoutError,
TrimLynkError,
)
client = TrimLynk()
try:
link = client.links.create(
original_url="https://example.com",
slug="my-custom-slug",
)
except AuthenticationError as err:
print(f"Invalid API key [request_id={err.request_id}]: {err.message}")
except InvalidRequestError as err:
print(f"Validation failure [request_id={err.request_id}]: {err.message}, details: {err.details}")
except IdempotencyConflictError as err:
print(f"Idempotency key reused with mismatched payload: {err.message}")
except ConflictError as err:
print(f"Custom slug already taken: {err.message}")
except RateLimitError as err:
print(f"Rate limited. Please retry after {err.retry_after} seconds.")
except TimeoutError as err:
print(f"Request timed out: {err}")
except NetworkError as err:
print(f"Connection failure: {err}")
except APIError as err:
print(f"API Error [{err.status_code} {err.code}]: {err.message}")
except TrimLynkError as err:
print(f"Unexpected SDK error: {err}")
Command Line Interface (CLI)
The trimlynk executable is automatically available upon installation.
Global Options
--json: Output raw, machine-readable JSON (ideal for piping tojqor CI automation).-q,--quiet: Output only primary resource IDs/URLs, suppressing decorative headers.--api-key KEY: Override active TrimLynk API key for a command.--environment {live, test}: Select target environment (liveortest).--base-url URL: Override API base URL.
Representative Workflows
# Authentication & Status
trimlynk auth login
trimlynk auth status --check
trimlynk auth logout
# Links Management
trimlynk links create https://example.com/promo --slug spring26 --tag marketing
trimlynk links list --limit 20
trimlynk links get spring26
trimlynk links update spring26 --title "Spring Sale Extended"
trimlynk links delete spring26 --yes
# Analytics
trimlynk analytics summary
trimlynk analytics link spring26
# Conversions
trimlynk conversions create --link-id url_abc123 --event-name purchase --revenue 149.99 --order-id ord_001
trimlynk conversions list
# Marketing Campaigns
trimlynk campaigns create --name "Q3 Growth" --goal 5000 --status active
trimlynk campaigns list
# Webhooks & Testing
trimlynk webhooks list
trimlynk webhooks test <webhook_id>
trimlynk webhooks deliveries <webhook_id>
Local Webhook Tunneling (trimlynk webhooks listen)
Stream live webhook events directly to your local application backend without exposing a public IP:
# Forward incoming live webhooks to your local app (auto-detects local ngrok tunnel)
trimlynk webhooks listen --forward-to http://localhost:8000/webhooks/trimlynk
# Filter for specific events
trimlynk webhooks listen --event click.created --event conversion.created
# Specify an explicit tunnel URL
trimlynk webhooks listen --tunnel-url https://my-domain.ngrok-free.dev --forward-to http://localhost:8000/webhooks/trimlynk
The listener automatically provisions an ephemeral webhook, streams deliveries in real-time, and cleanly tears down the webhook upon exit (Ctrl+C).
Optional Integrations
Secure OS Credential Storage ([keyring])
pip install "trimlynk[keyring]"
Enables the CLI to read and store API keys using your operating system's native credential manager (macOS Keychain, Windows Credential Manager, or Secret Service). If omitted, the CLI gracefully falls back to ~/.trimlynk/credentials.json with restricted permissions (0o600).
Pandas / Data Science Export ([data])
pip install "trimlynk[data]"
Export analytics telemetry and paginated link collections directly into Pandas DataFrames for Jupyter notebooks, ETL jobs, and BI pipelines:
summary = client.analytics.get()
# Export breakdown tables
devices_df = summary.to_dataframe("devices") # columns: ['device', 'clicks']
countries_df = summary.to_dataframe("countries") # columns: ['country', 'clicks']
referrers_df = summary.to_dataframe("referrers") # columns: ['referrer', 'clicks']
# Export all breakdowns as a dictionary of DataFrames
all_dfs = summary.to_dataframe("all")
print(all_dfs["devices"].head())
# Export a paginated list of links directly to a DataFrame
links_df = client.links.list().to_dataframe()
Requirements
- Python:
3.9,3.10,3.11,3.12,3.13,3.14,3.15 - Zero Runtime Dependencies: The core SDK and CLI require no third-party libraries and operate entirely on the Python standard library.
Security & Data Protection
- Small Dependency Surface: The core SDK requires zero third-party packages, keeping runtime supply-chain risks minimal.
- Timing-Safe Cryptography: HMAC-SHA256 signature verification uses
hmac.compare_digestto prevent timing attacks. - Replay Attack Protection: Webhook timestamp validation rejects dispatches outside the configured tolerance window (default 300s).
- Credential Masking: API keys are masked in
__repr__and string representations to prevent accidental leakage in logs. - Encrypted In-Transit: HTTPS is enforced by default (
https://api.trimlynk.com). - Strict Permission Fallback: Local CLI credential files are created with restricted file permissions (
0o600on POSIX systems).
API & SDK Versioning
- API Version: Targets the TrimLynk Developer API v1 (
/api/v1/developer/*). Outbound requests transmitX-Trimlynk-API-Version: 1. - SDK Version: The SDK adheres to Semantic Versioning 2.0.0 (
MAJOR.MINOR.PATCH).- MAJOR: Breaking changes to public interfaces or dropping minimum Python runtime support.
- MINOR: Backward-compatible feature additions, new resource clients, or CLI subcommands.
- PATCH: Backward-compatible bug fixes, performance optimizations, and documentation updates.
Official Links & Support
| Resource | URL | Purpose |
|---|---|---|
| Platform Dashboard | https://trimlynk.com | Main dashboard, branded domains, and analytics |
| Developer Hub | https://trimlynk.com/developers | API keys, scopes, telemetry, and rate limits |
| SDK Documentation | https://trimlynk.com/developers/sdks | Python client library documentation and guides |
| OpenAPI Reference | https://trimlynk.com/api-docs | Interactive endpoint explorer & JSON spec |
| Webhooks Guide | https://trimlynk.com/developers/webhooks | HMAC signature verification & event schema |
| PyPI Registry | https://pypi.org/project/trimlynk/ | Official package release and installation |
| Support & Inquiries | https://trimlynk.com/contact | Developer support and security inquiries |
| Terms of Service | https://trimlynk.com/terms | Commercial terms of service and acceptable use |
| Privacy Policy | https://trimlynk.com/privacy | Privacy policy and data protection |
Get Started
Ready to integrate TrimLynk link infrastructure?
- Create your account at trimlynk.com.
- Generate an API key in Settings > API Keys (Developer Hub).
- Install the SDK:
pip install trimlynk.
Proprietary License
Proprietary Commercial License (All Rights Reserved).
Copyright (c) 2026 TrimLynk. Licensed under the TrimLynk End-User License Agreement. This software package is provided solely for the purpose of integrating with and consuming TrimLynk APIs and services. Reverse engineering, decompilation, resale, sublicensing, or unauthorized redistribution is strictly prohibited. For complete terms, visit TrimLynk Terms of Service and Privacy Policy.
Metadata
Release files for trimlynk 1.1.2
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| trimlynk-1.1.2.tar.gz | 80.3 kB | Without provenance | Details for trimlynk-1.1.2.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| trimlynk-1.1.2-py3-none-any.whl | Python 3 | none | any | Details for trimlynk-1.1.2-py3-none-any.whl |
Total release size: 145.8 kB
Release files / trimlynk-1.1.2.tar.gz
| Download URL | trimlynk-1.1.2.tar.gz |
|---|---|
| Size | 80.3 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
efa2989b41a8c5ea919044476038259be0832f04215c34d6ec15ff92a4d7b2cd
|
|
BLAKE2b-256 checksum How to use checksums |
95939620811655685aba6167a4216f1c51d38f59ffd1b3de4c372af329ab6a2f
|
| 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.1.2-py3-none-any.whl
| Download URL | trimlynk-1.1.2-py3-none-any.whl |
|---|---|
| Size | 65.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
f65aa20c2e3c18f5b9d5b110c03c1de5becd04b3feabdafc25d73b5e132e2b8c
|
|
BLAKE2b-256 checksum How to use checksums |
dd508ca004f1abcfb4587d0aa00b719db0b3bca500c32d900082313f13ea2b10
|
| 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.1.2
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.