URL Shortener SDK for Node.js and Python
SendURL's official SDKs for Node.js and Python: install, add an API key, shorten links, page through them and read clicks and analytics, with typed errors.
SendURL has official URL shortener SDKs for Node.js and Python. Run npm install sendurl or pip install sendurl, add an API key, and one call returns a short link on snu.to with its QR address. Both wrap the whole REST API, links, clicks and analytics, and work on every plan, Free included; a few calls, such as setting a password or an expiry, need Pro and above.
Step 2: share the short link in place of the long one, in a message, a post or an email.
Step 3: sign up free to keep the link and see each click's country, device and referrer.
How to use the URL shortener SDK
The SDKs call the same URL shortener API as the console, so links made in code show up there too.
- Install the package.
npm install sendurl(orpnpm add,yarn add,bun add), orpip install sendurl. - Get an API key. Create a free account. Then open console.sendurl.to/api-keys, choose New key, pick its access and copy the key. It starts with
snu_. - Store it as
SENDURL_API_KEY. Both SDKs read that environment variable when you don't pass a key.
npm install sendurl
pip install sendurlThen create a link. In Node.js, save this as an ES module, so top-level await works:
import { SendURL } from "sendurl";
const sendurl = new SendURL(); // reads SENDURL_API_KEY
const link = await sendurl.links.create({
destinationUrl: "https://example.com/spring-sale",
title: "Spring sale",
});
console.log(link.shortUrl); // a random slug, such as https://snu.to/x7Kp2
console.log(link.qrUrl); // what a QR code of this link should encodeThe same call in Python:
from sendurl import SendURL
client = SendURL() # reads SENDURL_API_KEY
link = client.links.create(
destination_url="https://example.com/spring-sale",
title="Spring sale",
)
print(link["shortUrl"]) # a random slug, such as https://snu.to/x7Kp2
print(link["qrUrl"])The snippets below continue these two files, reusing sendurl, client and link: paste them in order, and in Python call client.close() at the end. Each run makes one new link. On Free you switch a link off with links.update(id, { active: false }); deleting is Starter and above.
Only the destination is required. To pick the name yourself, add slug (slug: "your-name-spring-2027"): a slug belongs to one link across all of snu.to, so choose one only you would use, and a taken one raises slug_taken, as the errors section below shows. Arguments are camelCase in JavaScript and snake_case in Python, while response keys are camelCase in both, exactly as the API sends them, so every field name in the API docs works as written.
If you'd rather see the raw HTTP requests behind these calls, read the REST API guide with curl and fetch.
Is there a URL shortener npm package?
Yes: sendurl on npm is the official SendURL client for JavaScript and TypeScript. It has zero runtime dependencies (it uses the platform's own fetch), ships ESM and CommonJS builds with type declarations, and runs on Node.js 18 or later, Deno, Bun and edge runtimes. The source is on GitHub at sendurl-to/sendurl-node.
TypeScript editors complete every field from the declarations; the snippets here are plain JavaScript, so they run as .mjs files. CommonJS works too: require("sendurl").
The Python SDK: sendurl on PyPI
sendurl on PyPI is the official URL shortener Python library for SendURL. It runs on Python 3.9 or later, depends only on httpx, and gives you a sync client (SendURL) and an async one (AsyncSendURL) with the same methods. The source is at sendurl-to/sendurl-python.
Responses are plain dicts, typed with TypedDicts and a py.typed marker.
List every link without handling pages
The API returns lists 10 items at a time with a cursor. The SDKs follow the cursor for you: list() walks every item and fetches the next page only when your loop reaches it.
for await (const item of sendurl.links.list({ status: "active", sort: "clicks_desc" })) {
console.log(item.slug, item.totalClicks);
}
const sale = await sendurl.links.list({ q: "spring" }).toArray(); // every match at oncefor item in client.links.list(status="active", sort="clicks_desc"):
print(item["slug"], item["totalClicks"])break out of the loop and no further page is requested. For one page with its extras, such as usage, use listPage() (list_page() in Python) and pass nextCursor back as cursor. Both take q, status, folderId, tagIds and sort.
Read clicks, stats and analytics
Every click a link gets is recorded on every plan, with its time, country, device, browser, operating system, referrer and whether it was a QR scan. The SDKs read it three ways, the same numbers the console's Link Analytics shows.
- One link's clicks, newest first:
links.clicks.list(linkId). A QR scan hassourceset to"qr". - Clicks per day for one link, all time:
links.stats(linkId)returns[{ date, count }, …]. - Analytics for the workspace, a folder or a link over a date range:
analytics.overview()for totals, a daily series and the top links, andanalytics.breakdown()by country, device, browser, OS, referrer or link.
const day = (daysAgo) => new Date(Date.now() - daysAgo * 86_400_000).toISOString().slice(0, 10);
// No tz: days are UTC, the API's default, matching the UTC dates above.
const overview = await sendurl.analytics.overview({ from: day(7), to: day(0) });
console.log(overview.kpis.clicks, overview.kpis.qrScans);
const countries = await sendurl.analytics.breakdown({ from: day(7), to: day(0), dimension: "country", limit: 10 });
for (const row of countries.rows) console.log(row.key, row.clicks);
for await (const click of sendurl.links.clicks.list(link.id)) {
console.log(click.clickedAt, click.country, click.device, click.source);
}from datetime import datetime, timedelta, timezone
today = datetime.now(timezone.utc).date() # UTC, the API's default tz
overview = client.analytics.overview(from_=today - timedelta(days=7), to=today)
print(overview["kpis"]["clicks"], overview["kpis"]["qrScans"])
print(client.links.stats(link["id"])) # [{"date": "2026-11-20", "count": 12}, ...]from_ has a trailing underscore because from is a Python keyword. Days are in UTC unless you pass tz; if you do, compute today's date in that zone too. Analytics ranges follow your plan: on Free they cover today and the 7 days before it, on Starter 30 days, and links.stats() and links.clicks stay all-time on every plan. The city and UTM breakdowns and unique visitors are Starter and above. Send analytics requests one at a time: a busy moment answers 503 analytics_unavailable, which the SDK retries after the wait the API asks for.
QR styles, UTM tags and deep links
These settings go on links.create() or, as here, on the link the script already made with links.update(), so a re-run makes no extra links:
await sendurl.links.update(link.id, {
iosUrl: "https://apps.apple.com/app/id123",
androidUrl: "https://play.google.com/store/apps/details?id=com.example",
});
try {
await sendurl.links.update(link.id, { qrStyle: { fg: "#1f2937", bg: "#ffffff", dots: "rounded", corners: "rounded" } });
} catch (error) {
if (error.code !== "plan_upgrade_required") throw error;
console.log("Custom colours are on Starter and above");
}from sendurl import PermissionDeniedError
client.links.update(
link["id"],
ios_url="https://apps.apple.com/app/id123",
android_url="https://play.google.com/store/apps/details?id=com.example",
)
try:
client.links.update(link["id"], qr_style={"fg": "#1f2937", "bg": "#ffffff", "dots": "rounded", "corners": "rounded"})
except PermissionDeniedError as e:
if e.code != "plan_upgrade_required":
raise
print("Custom colours are on Starter and above")- QR style: colours and the shape of the dots and corners, used when the console draws the code (
v: 1is added for you). On Free this custom colour answersplan_upgrade_required; Starter and above have every option. The encoded address staysqrUrl. More on QR Codes. - UTM tags go in the destination URL when you create the link (
https://example.com/spring-sale?utm_source=newsletter&utm_medium=email), and theutmbreakdown groups clicks by them on Starter and above. The free UTM builder writes the tags. UTM tracking explains the report. - Phones:
iosUrlandandroidUrlsend iPhone and Android visitors to their own address, such as your app's store page, on Pro and above. See Deep links.
Both SDKs also take password and expiresAt (expires_at), which are Pro and above, plus preview, abTest (ab_test), folderId and tagIds.
Handle errors by code
Each HTTP status has its own error class, carrying the API's stable code, a message and the full body. Branch on the code. The example reuses your first link's slug on purpose, so it always shows the slug_taken branch.
import { ConflictError, PermissionDeniedError } from "sendurl"; // move this line to the top of the file
try {
await sendurl.links.create({ destinationUrl: "https://example.com", slug: link.slug });
} catch (error) {
if (error instanceof ConflictError && error.code === "slug_taken") {
console.log("That slug is taken; pick another");
} else if (error instanceof PermissionDeniedError && error.code === "plan_upgrade_required") {
console.log(error.message); // for a paid feature, error.body.requiredPlan names the plan
} else {
throw error;
}
}from sendurl import ConflictError, PermissionDeniedError
try:
client.links.create(destination_url="https://example.com", slug=link["slug"])
except ConflictError as e:
if e.code != "slug_taken":
raise
print("That slug is taken; pick another")
except PermissionDeniedError as e:
body = e.body or {}
if e.code == "link_limit_reached":
print(f"{body['current']} of {body['limit']} links used")
elif e.code == "plan_upgrade_required":
print("Needs the", body.get("requiredPlan", "Pro"), "plan")
else:
raiseThe codes you'll meet most:
| Code | Class | When |
|---|---|---|
slug_taken | ConflictError | Another link already uses that slug |
plan_upgrade_required | PermissionDeniedError | The call needs a higher plan; for a paid feature, requiredPlan names it |
link_limit_reached | PermissionDeniedError | The workspace has used every link of its plan |
invalid_api_key | AuthenticationError | The key is unknown, revoked or expired |
validation_error | BadRequestError | A field is wrong; issues says which |
analytics_unavailable | ServiceUnavailableError | Analytics are busy; retried for you |
plan_upgrade_required is how a call for a paid feature answers on Free, such as a password, an expiry or a destination change; a delete on Free answers it too, without requiredPlan. Every plan and what it includes is on the Pricing page.
Retries, HTTPS and keeping the key safe
- Only reads are retried. GET requests are retried on network errors, timeouts and 429, 502, 503 or 504 answers, twice by default (
maxRetries/max_retries), honouringRetry-After. POST, PATCH and DELETE are never retried: a repeated create could make a second link, so after a connection error look for the link withlinks.list({ q: slug })first. - HTTPS only. The base URL must be
https://; plainhttp://is accepted only forlocalhost,127.0.0.1and::1, for testing against a local server. Redirects are never followed, so the key can't be carried to another host. - The key never shows up in output: not in errors,
String(client),JSON.stringify(client)orrepr(client). - Keep the key on the server. Code that runs in a browser or a mobile app hands the key to everyone who opens it. Use the SDK in your backend, a script or a serverless function, and read the key from an environment variable or a secret store.
Requests time out after 30 seconds (timeoutMs / timeout). The API allows about 50 requests per 10 seconds per IP address.
Async Python
AsyncSendURL has the same methods as SendURL. Await each call and use async for with list(). This script stands on its own:
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/spring-sale")
print(link["shortUrl"])
async for click in client.links.clicks.list(link["id"]):
print(click["clickedAt"], click["country"])
asyncio.run(main())It fits FastAPI and other asyncio code.
Run it on Cloudflare Workers and other edge runtimes
The Node.js package needs nothing but a global fetch, so it runs on Cloudflare Workers and other edge runtimes, Deno and Bun as is. Where there is no process.env, pass the key in:
import { SendURL } from "sendurl";
export default {
async fetch(request, env) {
const id = new URL(request.url).searchParams.get("id");
if (!id) return new Response("Missing id", { status: 400 });
const sendurl = new SendURL({ apiKey: env.SENDURL_API_KEY });
const link = await sendurl.links.get(id, { timeoutMs: 5_000 });
return Response.json({ shortUrl: link.shortUrl, clicks: link.totalClicks });
},
};Store the key with wrangler secret put SENDURL_API_KEY, never in wrangler.toml. To bound a call inside a request, pass an options object as the last argument of any method: { timeoutMs: 5_000 }, as above, or { signal } with an AbortSignal.
Plans and limits
The SDKs are free and MIT-licensed, and the API behind them comes with every plan, Free included.
| What you get | Free | Starter, $9 a month |
|---|---|---|
| Links | 25 links | 250 links a month |
| Analytics range | today and the 7 days before it | 30 days |
| Clicks and daily stats per link | all time | all time |
| QR code design | basic design on every link, small SendURL wordmark | every pattern, corner style, colour and frame, no wordmark |
| A/B tests | none | none (Pro and above: any number, up to 4 variants) |
Starter and above add destination changes, deleting links, the city and UTM breakdowns and unique visitors (distinct IP addresses); Pro and above add link passwords, expiry dates, deep links and A/B tests, all through the same SDK calls.
More on the API
- URL shortener API in Python: a CSV of links in, every click out, with plain HTTP
- MCP server set-up guide: let an AI assistant manage your links
- CSV export: every link in one file, from the console (Pro and above)
Set it up
Create a free account, make a key on the API keys page, and run shorten.mjs or shorten.py above.
Prefer a button to code? The URL shortener Chrome extension creates the same links from the toolbar.
Frequently asked questions
Call links.export() in Node.js, which streams a CSV file of every link matching your filters, or client.links.export_to_file("links.csv") in Python. The export covers links and is on Pro and above; clicks come from links.clicks.list().
Yes. When you create the key in the console, choose Custom and tick only the permissions it needs, such as links:read and analytics:read. A call outside them raises PermissionDeniedError with the code insufficient_scope.
In Node.js, links.update(id, { active: false }) switches a link off and links.update(id, { title: "New title" }) renames it, on every plan; in Python, client.links.update(link_id, active=False). Changing destinationUrl is on Starter and above.
Yes. Pass abTest (ab_test in Python) with two or more variants when you create or update a link, then end the test with links.pickWinner(id, variantId) (pick_winner in Python). A/B tests are on Pro and above, any number with up to 4 variants.
Shorten links from your code.
The REST API is on every plan, Free included: create links and read their clicks with an API key.