SendURL Python SDK
SendURL is a URL shortener with click analytics, QR codes and custom domains. This is the official Python client for its REST API (API reference): create short links and QR codes, organize them in folders and tags, and read click analytics.
- Sync (
SendURL) and async (AsyncSendURL) clients with the same methods - Typed responses (
TypedDicts) and apy.typedmarker - Lists you can iterate, with pagination handled for you
- One exception class per kind of error, carrying the API's stable error
code - GET requests retried on network errors, 429, 502, 503 and 504, honouring
Retry-After - Python 3.9 or later; its only dependency is
httpx
Install
pip install sendurl
Quick start
Create a free SendURL account, then create an API key on the console's API keys page, then:
from sendurl import SendURL
client = SendURL(api_key="snu_...") # or set SENDURL_API_KEY and call SendURL()
link = client.links.create(destination_url="https://example.com/launch", slug="launch")
print(link["shortUrl"]) # https://snu.to/launch
print(link["qrUrl"]) # the URL a QR code of this link should encode
for link in client.links.list(status="active"):
print(link["slug"], link["totalClicks"])
client.close()
You can use the client as a context manager instead, so it closes itself:
with SendURL() as client:
me = client.account.get()
print(me["plan"]["name"], me["usage"]["linksUsed"], "/", me["plan"]["linksLimit"])
Async
import asyncio
from sendurl import AsyncSendURL
async def main() -> None:
async with AsyncSendURL() as client:
link = await client.links.create(destination_url="https://example.com")
async for click in client.links.clicks.list(link["id"]):
print(click["clickedAt"], click["country"])
asyncio.run(main())
The async client has the same methods as the sync one. Await every call, and use async for
with the list() methods.
Responses
Every method returns the API's JSON as plain Python dicts and lists. The keys are camelCase,
as they are on the wire (link["shortUrl"], link["destinationUrl"]), so the
API reference applies as written. The TypedDicts in sendurl
(Link, LinkList, Click, Account, Overview, ...) describe them for your editor and type
checker. They are all total=False, so a field the server adds later shows up in the dict
and never breaks your code.
Arguments are snake_case keyword arguments and are mapped to the API's camelCase for you
(destination_url becomes destinationUrl, folder_id becomes folderId).
Reference
The examples below use the sync client; for the async client, add await (or async for).
Account
me = client.account.get() # GET /me
me["org"]["name"], me["plan"]["linksLimit"], me["usage"]["linksUsed"]
me["key"]["scopes"] # None = every scope
me["folder"] # the folder a folder-level key is limited to, else None
Links
A link can also send phones to mobile app targets, expire or ask for a password, carry a styled QR code and a custom link preview, and split its visitors in an A/B test.
from datetime import datetime, timezone
link = client.links.create(
destination_url="https://example.com/spring", # required
slug="spring", # default: a random slug
title="Spring campaign",
folder_id="…", # default: the Default folder (or a folder key's own)
domain_id="…", # a live domain (client.domains); can't be changed later
tag_ids=["…", "…"],
ios_url="https://apps.apple.com/app/id123", # where iPhone and iPad visitors go
android_url="https://play.google.com/store/apps/details?id=x",
expires_at=datetime(2027, 1, 1, tzinfo=timezone.utc), # Pro and above
password="s3cret!", # Pro and above; never returned to an API key
qr_style={"fg": "#1a1a2e", "bg": "#ffffff", "dots": "rounded", "corners": "dots"}, # "v": 1 is added
preview={"title": "Spring sale", "description": "Up to 40% off", "image": "https://…/card.png"},
ab_test={
"variants": [
{"id": "a", "url": "https://example.com/spring", "weight": 50},
{"id": "b", "url": "https://example.com/spring-b", "weight": 50},
]
},
)
link = client.links.get(link["id"]) # adds totalClicks, qrScans, tags, domain
client.links.delete(link["id"]) # paid plans; on Free, disable it instead
expires_at takes a timezone-aware datetime or an ISO 8601 string with an offset
("2027-01-01T00:00:00Z"). A naive datetime raises ValueError, because the API needs to
know the time zone.
Update changes only the fields you pass. Passing None clears a field (it is sent as JSON
null); leaving a field out leaves it as it is:
client.links.update(link_id, title="New title") # only the title changes
client.links.update(link_id, ios_url=None) # remove the iOS target
client.links.update(link_id, expires_at=None) # never expire
client.links.update(link_id, active=False) # disable the link
client.links.update(link_id, destination_url="https://…") # Pro and above
client.links.update(link_id, ab_test=None) # end the A/B test without a winner
The default of every update() argument is sendurl.NOT_GIVEN, which means "not passed".
A/B test winner: end a running test and make one variant's URL the destination:
client.links.pick_winner(link_id, variant_id="b") # POST /links/:id/ab-test/winner
List and search:
for link in client.links.list(
status=["active", "expired"], # any of: active, disabled, expired, protected, limit_reached
q="spring", # searches slug, destination and title
sort="clicks_desc", # created_desc (default), clicks_desc, clicks_asc
folder_id="…",
tag_ids=["…"], # links with any of these tags
):
...
page = client.links.list_page(limit=10) # one page, with summary, usage and pagination
page["summary"] # {"totalLinks", "activeLinks", "totalClicks"}, or None for very large workspaces
page["usage"] # {"linksUsed", "linksLimit"}
The clicks sorts follow the live click counter, so a link can move between pages while you
page through them; deduplicate by id if that matters.
Stats and clicks:
client.links.stats(link_id) # [{"date": "2026-11-01", "count": 12}, ...] all-time, UTC days with clicks
for click in client.links.clicks.list(link_id): # newest first
click["clickedAt"], click["country"], click["device"], click["source"] # "qr" for a QR scan
page = client.links.clicks.list_page(link_id, limit=10)
click = client.links.clicks.get(link_id, click_id)
A click never includes the visitor's IP address. On the Free plan city is None and
cityLocked is True.
CSV export of every link matching the filters, streamed:
with client.links.export(status="active") as csv: # GET /links/export.csv
for chunk in csv: # bytes
...
client.links.export_to_file("links.csv", folder_id="…") # returns the number of bytes written
On the async client, csv = await client.links.export(), then async with csv: and
async for chunk in csv:.
Analytics
Analytics dates are datetime.date objects or "YYYY-MM-DD" strings, inclusive, in tz (an IANA
name such as "Europe/Paris", default UTC). The range must lie within your plan's analytics
history (otherwise you get BadRequestError with code range_outside_history). Pass
folder_id or link_id to narrow the scope; without either an org key reads the whole
workspace.
from datetime import date
overview = client.analytics.overview(from_=date(2026, 11, 1), to=date(2026, 11, 7), tz="Europe/Paris")
overview["kpis"]["clicks"], overview["series"], overview["topLinks"], overview["breakdowns"]["country"]
top = client.analytics.breakdown(
from_="2026-11-01",
to="2026-11-07",
# link, country, device, browser, os, referrer, variant (needs link_id),
# and on Pro and above city and utm
dimension="country",
order="desc",
limit=10,
)
client.analytics.breakdown(from_="2026-11-01", to="2026-11-07", dimension="utm", by="campaign")
client.analytics.breakdown(from_="2026-11-01", to="2026-11-07", dimension="referrer", category="social")
client.analytics.breakdown(from_="2026-11-01", to="2026-11-07", dimension="city", count_only=True)
for click in client.analytics.clicks(from_="2026-11-01", to="2026-11-07", link_id=link_id):
click["clickedAt"], click["referrer"]["label"]
page = client.analytics.clicks_page(from_="2026-11-01", to="2026-11-07") # pagination.total on page 1
The utm breakdown reads the UTM parameters in each link's destination URL; the free UTM builder writes them for you.
from_ has a trailing underscore because from is a Python keyword. Send analytics requests
one at a time: when analytics are busy the API answers 503 analytics_unavailable, which the
client retries for you after Retry-After seconds.
Folders
for folder in client.folders.list(): # Default first; org-level keys only
folder["name"], folder["linksCount"]
page = client.folders.list_page()
folder = client.folders.create(name="Marketing")
Tags
for tag in client.tags.list():
tag["id"], tag["name"], tag["color"], tag["linksCount"]
page = client.tags.list_page() # adds usage: {"tagsUsed", "tagsLimit"}
Tags are created and edited in the console; use their ids in tag_ids.
Domains
Read only for API keys: custom domains are added in the console.
for domain in client.domains.list():
domain["hostname"], domain["type"], domain["status"] # subdomain | custom; pending | active | failed
page = client.domains.list_page()
domain = client.domains.get(domain_id)
Pagination
Every list endpoint returns at most 10 items per page. Each resource gives you two ways to read it:
list(...)returns an iterator over every item. It fetches the next page (followingpagination.nextCursor) only when you reach the end of the current one, and nothing at all until you start iterating. Itslimitargument is the page size (1-10), not a total.list_page(..., cursor=None)returns one page as the API sends it (the items,pagination, and extras such assummaryandusage). Passpage["pagination"]["nextCursor"]ascursorto read the next page.
page = client.links.list_page()
while True:
for link in page["links"]:
...
if not page["pagination"]["hasMore"]:
break
page = client.links.list_page(cursor=page["pagination"]["nextCursor"])
Errors
Every API error raises a subclass of sendurl.SendURLError:
| Exception | When |
|---|---|
BadRequestError |
400: validation_error (see issues), range_outside_history, ... |
AuthenticationError |
401: missing, invalid, revoked or expired API key |
PermissionDeniedError |
403: insufficient_scope, plan_upgrade_required (a paid plan feature), link_limit_reached, ... |
NotFoundError |
404: link_not_found, click_not_found, domain_not_found, ... |
ConflictError |
409: slug_taken, project_name_taken, domain_not_active |
UnprocessableEntityError |
422: unsafe_destination, too_many_urls |
RateLimitError |
429 |
InternalServerError |
5xx |
ServiceUnavailableError |
503 (a subclass of InternalServerError): analytics_unavailable, export_unavailable, domains_unavailable |
APIConnectionError |
no response: DNS failure, refused or reset connection |
APITimeoutError |
the request timed out (a subclass of APIConnectionError) |
Each error carries:
status_code: the HTTP status (Nonefor connection errors)code: the API's stable error code. Branch oncode, never onmessage.message: a sentence for a personissues: the field issues of avalidation_errorbody: the whole JSON error body, with extra fields such aslimit,current,featureandrequiredPlanretry_after: seconds to wait, when the API said so
from sendurl import ConflictError, PermissionDeniedError
try:
client.links.create(destination_url="https://example.com", slug="launch")
except ConflictError as e:
if e.code == "slug_taken":
...
except PermissionDeniedError as e:
if e.code == "link_limit_reached":
print(f"{e.body['current']} of {e.body['limit']} links used")
elif e.code == "plan_upgrade_required":
print("Needs the", e.body["requiredPlan"], "plan")
Retries and timeouts
GET requests are retried up to max_retries times (default 2) on connection errors and
timeouts, and on 429, 502, 503 and 504 responses. The client waits for Retry-After seconds
when the API sends it (at most 60), otherwise it backs off exponentially with jitter
(about 0.5 s, then 1 s, then 2 s, ...).
POST, PATCH and DELETE are never retried: the API has no idempotency key, so retrying a
create could make the same link twice. If one of them fails with a connection error, check
whether it went through (for example with links.list(q=slug)) before trying again.
Each request times out after timeout seconds (default 30).
Configuration
import httpx
from sendurl import SendURL
client = SendURL(
api_key="snu_...", # default: the SENDURL_API_KEY environment variable
base_url="https://api.sendurl.to/api/v1", # default: SENDURL_BASE_URL, else production
timeout=30.0, # seconds, or an httpx.Timeout
max_retries=2, # retries for GET requests; 0 turns them off
http_client=httpx.Client(proxy="http://proxy:8080"), # optional: your own httpx client
)
AsyncSendURL takes the same arguments, with an httpx.AsyncClient as http_client. A client
you pass in is yours to close: close() / aclose() close only the one the SDK created.
base_url must be https://; plain http:// is accepted only for localhost, 127.0.0.1
and ::1 (a local platform), so the key never crosses a network in clear text. Redirects are
never followed, even by an http_client created with follow_redirects=True: a 3xx answer
raises SendURLError (usually a wrong base_url).
The API key is never included in repr(client) or in any error message. Keep it on the server:
a key shipped in browser or mobile code can be read by anyone.
Scopes
An API key can be limited to some scopes. Each method needs one:
| Scope | Methods |
|---|---|
links:read |
links.list, list_page, get, stats, export, links.clicks.* |
links:write |
links.create, update, pick_winner |
links:delete |
links.delete |
analytics:read |
analytics.* |
workspace:read |
account.get, folders.list, tags.list, domains.* |
folders:write |
folders.create |
A key without the scope gets PermissionDeniedError with code insufficient_scope.
Local development
To point the client at a SendURL platform running on your machine:
client = SendURL(api_key="snu_...", base_url="http://localhost:1911/api/v1")
To work on this library:
uv sync # create .venv with the dev tools
uv run ruff check .
uv run ruff format --check .
uv run mypy
uv run pytest
uv build
The integration tests in tests/test_integration.py run against a real platform and are
skipped unless both variables are set:
SENDURL_BASE_URL=http://localhost:1911/api/v1 SENDURL_API_KEY=snu_... uv run pytest tests/test_integration.py -v
They create one link and delete it at the end (on the Free plan, where deleting isn't allowed, they disable it instead).
Releasing
For maintainers. Releases are published from GitHub, never from a laptop:
- Bump the version in both
pyproject.toml(version) andsrc/sendurl/_version.py(__version__, which theUser-Agentcarries) to the same PEP 440 version, such as0.2.0or0.2.0rc1, and add its section toCHANGELOG.md(## [x.y.z] - YYYY-MM-DD). A unit test and the release build both fail when the two differ, so a mismatched version is never published. - Merge to
main. - The Release workflow (
.github/workflows/release.yml) runs on anypyproject.tomlchange onmain. If that exact version isn't on PyPI yet, it runs ruff, mypy and the tests, builds the sdist and wheel, publishes them to PyPI with Trusted Publishing (no PyPI token exists), and creates thevx.y.ztag on that commit with a GitHub Release whose notes are the version's CHANGELOG section. Ana,b,rcordevversion is marked as a prerelease on GitHub (pip installs it only when asked for it explicitly). A version already on PyPI is not published again, so otherpyproject.tomledits publish nothing.
It can also be started by hand (Actions → Release → Run workflow, on main). PyPI records no
commit for a release, so when a version is already on PyPI but has no GitHub Release yet (a
failed run), the run creates it only when you give target_sha: the full SHA of the commit on
main it was published from. Without it, the run only warns.
The very first release (0.1.0) needs two one-time steps: register a pending trusted
publisher on PyPI (PyPI project name sendurl, owner sendurl-to, repository sendurl-python,
workflow release.yml, environment pypi), then run the workflow once by hand (Actions → Release → Run workflow, on
main). The commit that added the workflow doesn't change pyproject.toml, so pushing it starts
no run.
Releases run from main only. PyPI trusts exactly this repository, the workflow file
release.yml and the GitHub environment pypi, whose deployment branch policy allows only
main. Renaming the workflow file breaks publishing until the trusted publisher is updated.
Links
- SendURL website: the URL shortener this SDK talks to
- API reference: every endpoint, field and error code
- Plans and pricing: limits and the features each plan includes
- Free URL shortener: shorten a link without an account
- Free link tools: a UTM builder, a QR code generator and more
- Guides and the SendURL blog
- SendURL console: your links, analytics and API keys
License
MIT, see LICENSE.
Metadata
Release files for sendurl 0.1.0
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 |
|---|---|---|---|---|
| sendurl-0.1.0.tar.gz | 38.7 kB | With provenance | Details for sendurl-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| sendurl-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for sendurl-0.1.0-py3-none-any.whl |
Total release size: 71.2 kB
Release files / sendurl-0.1.0.tar.gz
| Download URL | sendurl-0.1.0.tar.gz |
|---|---|
| Size | 38.7 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
bb3ada9bd98874f4e0a0cf409dc69a973f0196f27c53abbdf8a2d0b6bdca1912
|
|
BLAKE2b-256 checksum How to use checksums |
07c59a7e6720842c314aa757f29823e34ac5060e2853fcd7828d641a670d9887
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
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.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.
Transparency logRelease files / sendurl-0.1.0-py3-none-any.whl
| Download URL | sendurl-0.1.0-py3-none-any.whl |
|---|---|
| Size | 32.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
d3bbb445588a5a1f07274699506d767b82f41b69d1ca2418bbe8c23a7ba1c553
|
|
BLAKE2b-256 checksum How to use checksums |
c1b925c4f525843608d6468be4900dafcca29b0b1b5aac5a39092d3af80372e7
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
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.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.
Transparency logSecurity for sendurl 0.1.0
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.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for sendurl-0.1.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.
Transparency logA 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.