Skip to main content
SendURL, home
FeaturesBy MikeUpdated 13 min read

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.

Illustration, not a screenshot

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.

  1. Install the package. npm install sendurl (or pnpm add, yarn add, bun add), or pip install sendurl.
  2. 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_.
  3. Store it as SENDURL_API_KEY. Both SDKs read that environment variable when you don't pass a key.
InstallShell
npm install sendurl
pip install sendurl

Then create a link. In Node.js, save this as an ES module, so top-level await works:

shorten.mjsJavaScript
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 encode

The same call in Python:

shorten.pyPython
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.

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.

Node.js (shorten.mjs, continued)JavaScript
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 once
Python (shorten.py, continued)Python
for 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 has source set 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, and analytics.breakdown() by country, device, browser, OS, referrer or link.
Node.js (shorten.mjs, continued)JavaScript
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);
}
Python (shorten.py, continued)Python
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.

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:

Node.js (shorten.mjs, continued)JavaScript
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");
}
Python (shorten.py, continued)Python
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: 1 is added for you). On Free this custom colour answers plan_upgrade_required; Starter and above have every option. The encoded address stays qrUrl. 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 the utm breakdown groups clicks by them on Starter and above. The free UTM builder writes the tags. UTM tracking explains the report.
  • Phones: iosUrl and androidUrl send 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.

Node.js (shorten.mjs, continued)JavaScript
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;
  }
}
Python (shorten.py, continued)Python
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:
        raise

The codes you'll meet most:

CodeClassWhen
slug_takenConflictErrorAnother link already uses that slug
plan_upgrade_requiredPermissionDeniedErrorThe call needs a higher plan; for a paid feature, requiredPlan names it
link_limit_reachedPermissionDeniedErrorThe workspace has used every link of its plan
invalid_api_keyAuthenticationErrorThe key is unknown, revoked or expired
validation_errorBadRequestErrorA field is wrong; issues says which
analytics_unavailableServiceUnavailableErrorAnalytics 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), honouring Retry-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 with links.list({ q: slug }) first.
  • HTTPS only. The base URL must be https://; plain http:// is accepted only for localhost, 127.0.0.1 and ::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) or repr(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:

async_clicks.pyPython
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:

worker.jsJavaScript
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 getFreeStarter, $9 a month
Links25 links250 links a month
Analytics rangetoday and the 7 days before it30 days
Clicks and daily stats per linkall timeall time
QR code designbasic design on every link, small SendURL wordmarkevery pattern, corner style, colour and frame, no wordmark
A/B testsnonenone (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

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().

Shorten links from your code.

The REST API is on every plan, Free included: create links and read their clicks with an API key.

Keep reading

More: the SendURL blog, all link tracking guides and how-to answers.