Skip to content

URL shortener API: free APIs compared, and how to use one from code

Free URL shortener APIs compared (Bitly, Rebrandly, Short.io, TinyURL, BN Shortener), what to check, and curl, Python and Node examples to create links.

By Shortlen Editorial Updated 11 min read

A soft beige still life of interlocking blocks and switches, suggesting an automated system
The short answerA URL shortener API lets your code create short links, change them and read their clicks over HTTP instead of a dashboard. With BN Shortener you send POST https://b1.lc/api/v1/links with your key in the X-API-Key header and a JSON body such as {"url": "https://example.com/sale"}; the answer contains the new short_url. API access is included on every plan, Free too.

Key takeaways

  • A shortener API does three jobs: create links, change them later, and report who clicked. Check all three before you choose one.
  • BN Shortener's REST API lives at https://b1.lc/api/v1 and is included on every plan; the Free tier allows 1,000 requests a minute.
  • Send the key in the X-API-Key header, never in a URL, and give each integration its own key with only the permissions it needs.
  • Add an Idempotency-Key to every write so a retry after a timeout never creates a second link.
  • Use bulk endpoints for volume and webhooks for clicks, instead of looping single calls or polling statistics.
  • Python (pip install bn-shortener) and TypeScript (npm install @bn-shortner/shortener) SDKs are published, alongside plain HTTP and the bn command line.

A URL shortener API lets your application create short links, change where they point and read their clicks without anyone opening a dashboard. This guide explains what a good shortener API should give you, then walks through working requests against the BN Shortener API (the service behind Shortlen) in curl, Python and Node, including the parts most tutorials skip: retries, rate limits and errors.

What does a URL shortener API do?

At its simplest, a shortener API turns a long URL into a short one. In production you need more than that. A useful API covers three jobs:

  1. Create: shorten a URL, optionally with your own back-half, your own domain, a title, tags and tracking.
  2. Manage: change the destination later without changing the short link, expire it, disable it, move it into a campaign.
  3. Measure: report clicks by date, country, device and referrer, ideally with bots and link previews filtered out.

Typical uses are product features (a “share” button that creates a link per user), marketing automation (one tagged link per email, ad or SMS), and internal tooling (a CMS that shortens every new article). If you only ever need the first job once, a dashboard is enough. If you need any of them repeatedly, an API saves hours and removes copy-paste mistakes.

What should you check before choosing a shortener API?

Most comparison posts list vendors. A checklist travels better, because plans change:

CheckWhy it mattersBN Shortener
API on the free planYou can build and test before payingYes, every plan (“Basic API access” on Free)
Rate limitDecides how fast a batch job can run1,000 requests/minute on Free; 3,000 Pro; 10,000 Business; 100,000 Enterprise
Bulk endpointOne request instead of a thousandUp to 1,000 links per request
Safe retriesA timeout should not create duplicatesIdempotency-Key on every POST, PUT, PATCH and DELETE
Error formatYour code can switch on a stable typeRFC 9457 problem details, 27 documented error types
Custom domainsLinks on go.yourbrand.comYes, added in the dashboard, used by name in the API
Click data qualityBots and previews inflate countsPeople only by default; bots reported separately
WebhooksPush instead of polling32 events, signed deliveries (Pro and higher)
SpecificationGenerate clients, import into PostmanOpenAPI 3.1, 182 operations, Postman collection

Two more questions are worth asking any provider: what happens to existing links if you downgrade (BN’s answer: plan limits only restrict creating new items, existing links keep working), and whether destinations are checked for phishing before a link goes live (BN scans every destination against threat sources such as PhishTank, URLhaus and SURBL when the link is created and on every change).

An API quickstart code card next to tiles for the REST API, webhooks and MCP
One account, three ways in: the REST API, webhooks and the MCP server for AI assistants.

Free URL shortener APIs compared

What each provider’s own pricing page listed for its free plan, checked on 24 October 2026. Limits are measured differently (per month, per minute, per second, per account lifetime), so read each row in its own unit.

ProviderAPI on the free planFree-plan limit, as listedWorth knowing
BN ShortenerYes, the same endpoints as paid plans1,000 requests a minute; 100 new links a monthBulk create up to 1,000 links per request; people-only click counts
BitlyYes1,000 API requests a monthThe Free plan is listed “with ads”
RebrandlyYes100 calls a minute; 10 links a monthPaid plans raise the link allowance
Short.ioRate limit listed for every plan50 requests a second; 1,000 links by API or bulk; 1,000 branded links over the account’s lifetimeThe lifetime cap is one-time, not monthly
TinyURLPublishes an API that needs an account tokenNot confirmed: the pricing page did not load as text when we checkedCheck the plan before building on it

For a hobby script that makes a few links a week, any of these works. For a product feature or a campaign tool, the limits that bite are links per month and requests per minute, and the question that matters long term is what happens to links made through the API when you stop paying. Our guides to shortening YouTube, Amazon and Google Drive links show common things people automate.

How do I get an API key?

  1. Start free at b1.lc and verify your email.
  2. In the dashboard open Integrations > API (the API Portal) and create a key.
  3. Give it only the permissions it needs. There are five: read, write, delete, webhooks and admin. New keys default to read + write, which is right for a script that creates links.
  4. Copy the key once into an environment variable. It is shown only at creation; BN stores a hash.
export BN_API_KEY="bn_live_..."

A few habits that save trouble later: one key per integration (so you can rotate or revoke one without breaking the others), an expiry date and allowed IP ranges on keys created through the API (POST /api/v1/keys) for contractors or experiments, and the account-wide country rules for integrations that only ever run from your servers. You can keep up to 25 active keys per account.

If you are building something other people connect to their own BN account, do not ask them for a key. Use OAuth 2.1 instead: authorization code with PKCE, or the device flow (they approve a code at b1.lc/device). Access tokens last one hour, refresh tokens 90 days, and users can disconnect your app at any time.

One request. The key goes in the X-API-Key header, never in the URL.

curl -X POST https://b1.lc/api/v1/links \
  -H "X-API-Key: $BN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://example.com/autumn-sale", "title": "Autumn sale", "tags": ["email", "autumn"]}'

The answer is a standard envelope with success, data and meta:

{
  "success": true,
  "data": {
    "id": 1612,
    "short_code": "AbC9",
    "short_url": "https://b1.lc/AbC9",
    "domain": "b1.lc",
    "original_url": "https://example.com/autumn-sale",
    "title": "Autumn sale"
  },
  "meta": { "request_id": "req_e3dd900343c76f6ff76f8495", "api_version": "v1" }
}

A random code is 4 characters, so the whole link, b1.lc/AbC9, is 10 characters long. Before the link goes live the destination is threat-scanned, and a Launch Check runs in the background.

The fields you will use most

FieldWhat it does
url (required)The destination, http or https
custom_codeYour own back-half, up to 50 characters, e.g. spring-sale
domainb1.lc (default), b0.lc, or one of your verified custom domains
titleA label for you; detected from the page when empty
tagsLabels for filtering, e.g. ["email", "autumn"]
privateA 9-character code nobody can guess (Pro and higher; not with custom_code)
conversion_trackingAdds a click code (bn_cid) so your site can report sales and sign-ups
gs1_gtinA product barcode number for a GS1 Digital Link QR code

The create-link reference lists the rest (expiry, password, campaign, UTM tags, redirect type and more). If you are deciding between redirect types, our guide to 301 vs 302 redirects explains the trade-offs.

How do I call it from Python or Node?

These examples use plain HTTP; the SDKs do the same retries for you. Both reuse the same Idempotency-Key on a retry, which is the detail that keeps a flaky network from creating duplicate links.

Python (with the requests package):

import os, time, uuid, requests

API = "https://b1.lc/api/v1"
KEY = os.environ["BN_API_KEY"]

def shorten(url, **fields):
    idem = str(uuid.uuid4())          # one key per logical request
    for attempt in range(4):
        r = requests.post(
            f"{API}/links",
            json={"url": url, **fields},
            headers={"X-API-Key": KEY, "Idempotency-Key": idem},
            timeout=10,
        )
        if r.status_code == 429 or r.status_code >= 500:
            time.sleep(int(r.headers.get("Retry-After", 2 ** attempt)))
            continue
        if not r.ok:
            problem = r.json()        # RFC 9457 problem details
            raise RuntimeError(f"{problem['type']}: {problem.get('errors')}")
        return r.json()["data"]["short_url"]
    raise RuntimeError("gave up after retries")

print(shorten("https://example.com/autumn-sale", title="Autumn sale", tags=["email"]))

Node 18+ (built-in fetch):

const res = await fetch("https://b1.lc/api/v1/links", {
  method: "POST",
  headers: {
    "X-API-Key": process.env.BN_API_KEY,
    "Content-Type": "application/json",
    "Idempotency-Key": crypto.randomUUID(),
  },
  body: JSON.stringify({ url: "https://example.com/autumn-sale", custom_code: "autumn-sale" }),
});
const body = await res.json();
if (!res.ok) throw new Error(`${body.type}: ${JSON.stringify(body.errors)}`);
console.log(body.data.short_url);

How do I read clicks?

Use the link’s id from the create response:

curl "https://b1.lc/api/v1/links/1612/stats?period=7d" -H "X-API-Key: $BN_API_KEY"

period takes 7d, 30d, 90d, 1y or all. The data.summary object has total_clicks, unique_clicks, bot_clicks, mobile_clicks and more, plus a daily timeline. Three options are worth knowing:

  • People only by default. Bots, crawlers and link previews (the fetch WhatsApp or Slack makes to draw a card) are left out. Add include_bots=true if you want them in the totals; they are always reported as their own number either way.
  • Drill-down filters. country=DE, device=Mobile or referrer=instagram.com narrow every figure.
  • Compare. compare=true adds the same-length period just before, so a weekly report can show the change without a second call.

For a live view there is a Server-Sent Events stream at GET /api/v1/links/{id}/clicks/stream, and a click export as CSV or JSON. Link stats also include an ai_assistants figure for visits from ChatGPT, Claude, Perplexity and other assistants; see how to track traffic from ChatGPT.

An analytics panel separating clicks by people from filtered bots, with illustrative numbers
Statistics count people; bots and link previews are reported separately (illustrative numbers).

Do not loop over the single-create endpoint. POST /api/v1/links/bulk takes a links array of up to 1,000 objects with the same fields as a single link, and answers with one result per item, in order, so you can retry only the ones that failed:

curl -X POST https://b1.lc/api/v1/links/bulk \
  -H "X-API-Key: $BN_API_KEY" -H "Content-Type: application/json" \
  -H "Idempotency-Key: 5b0a3c1e-2f7d-4e61-9a7b-0c4d8e2f1a63" \
  -d '{"links": [{"url": "https://shop.example.com/shoes", "title": "Shoes"},
                 {"url": "https://shop.example.com/bags", "title": "Bags"}]}'

Each result has index, success and, when it worked, data.short_url. For moving links from another shortener’s CSV, POST /api/v1/links/import has a dry-run mode; our guide to bulk shortening links from a CSV covers both, plus the no-code options.

What happens when something goes wrong?

Every error is an RFC 9457 problem with Content-Type: application/problem+json. Switch on type, which is stable, not on the human-readable title or detail:

{
  "type": "https://b1.lc/docs/errors/validation-failed",
  "title": "Validation Failed",
  "status": 422,
  "errors": [{ "field": "url", "code": "INVALID_URL", "message": "URL must use http:// or https:// scheme" }],
  "trace_id": "req_e3dd900343c76f6ff76f8495"
}

The ones to handle explicitly:

Status and typeMeaningWhat your code should do
401 missing-api-key / invalid-api-keyNo key, or a wrong or revoked oneStop and alert; retrying will not help
403 insufficient-permissionsThe key lacks read, write, delete or adminFix the key’s permissions
409 code-existsYour custom_code is takenPick another code or let BN choose
422 validation-failedA field is invalid; see errors[]Fix the input
422 security-blockedThe destination is on a threat listDo not retry; check the URL
402 plan-limit-reachedThe request would pass a plan limitSurface to a human
429 rate-limit-exceededToo many requests this minuteWait Retry-After seconds, then continue

Every response carries X-RateLimit-Limit, X-RateLimit-Remaining and reset headers, so a batch job can slow down before it hits the wall. Quote the trace_id if you contact support.

Safe retries in one paragraph

Networks drop answers. If you resend a create request without protection, you may get two links. Send Idempotency-Key with a unique value (a UUID) on writes: BN stores the first answer for 24 hours and replays it for a retry with the same key, marked Idempotency-Replayed: true. The same key with a different body returns 422; the same key while the first request is still running returns 409 with Retry-After. The header is being standardised at the IETF, and the BN docs page on safe retries has the full table.

How do webhooks fit in?

Polling statistics every minute wastes your rate limit. Webhooks push events to your endpoint instead: link.clicked, link.created, qr.scanned, link.converted, guardian.incident_opened and 27 others. Deliveries are signed with an X-BN-Signature header (t=...,v1=..., HMAC-SHA256) and a GitHub-style X-Hub-Signature-256 header, retried with growing delays (up to 6 hours apart), and can be redelivered from the log. A webhook is switched off after 10 failed deliveries in a row, so watch your endpoint. Verify signatures exactly as the webhooks documentation describes before you trust a payload.

Is there an SDK or a command line?

  • bn command line: available today. Download it from b1.lc/cli/bn (one file, Python 3.9+, Linux, macOS and Windows, with a published checksum). It covers shortening, stats, QR codes, Launch Check, bulk files and any raw API call (bn api GET /usage), with --json output and exit codes that work in CI.
  • Python SDK: pip install bn-shortener (PyPI); it also installs the bn command line. TypeScript SDK: npm install @bn-shortner/shortener (npm, Node 20+, browsers, Workers). The docs show SDK code next to curl.
  • Also released: the MCP local bridge npx -y @bn-shortner/shortener-mcp, the n8n community node n8n-nodes-bn-shortener, and the GitHub Action uses: BN-Shortner/bn-shortener-action@v1 (not in the Marketplace yet). Source code is at github.com/BN-Shortner, and every SDK, plugin and connector is listed with its status on the integrations page.
  • Every docs page has code in six languages, an OpenAPI 3.1 file and a Postman collection to download, and llms.txt for AI coding tools.

If you would rather ask an assistant than write code, the same account works through MCP: see manage links with AI assistants.

A production checklist

  • Key in an environment variable or secret store, with only the permissions it needs.
  • Idempotency-Key on every write, reused on retries.
  • Retry on 429 and 5xx with Retry-After; never retry 401, 403 or security-blocked.
  • Errors parsed by type, field problems read from errors[].
  • Bulk endpoint for anything over a handful of links.
  • Webhooks for clicks, with signatures verified, instead of polling.
  • X-BN-Client: yourapp/1.0 header so usage per integration shows up in GET /usage.
  • Custom domain set up in the dashboard before you send its name in domain.

Start building

The API, the bn command line and the MCP server are all usable today, on the Free plan too; webhooks come with Pro and higher. Create a free account at b1.lc, make a key, and your first short link is one curl command away. See what each plan includes and the developer platform for the full picture.

Sources

  1. Quickstart, BN Shortener developer docs, undated. Checked 2026-10-23.
  2. Create Link (API reference), BN Shortener developer docs, undated. Checked 2026-10-23.
  3. Authentication and permissions, BN Shortener developer docs, undated. Checked 2026-10-23.
  4. Safe retries with Idempotency-Key, BN Shortener developer docs, undated. Checked 2026-10-23.
  5. Errors, BN Shortener developer docs, undated. Checked 2026-10-23.
  6. RFC 9457: Problem Details for HTTP APIs, IETF / RFC Editor, 2023-07. Checked 2026-10-23.
  7. The Idempotency-Key HTTP Header Field (draft-ietf-httpapi-idempotency-key-header-08), IETF HTTPAPI Working Group, 2026-10-22. Checked 2026-10-23.
  8. Bitly pricing (API requests per plan), Bitly, as published on 24 October 2026. Checked 2026-10-24.
  9. Rebrandly pricing (API calls per plan), Rebrandly, as published on 24 October 2026. Checked 2026-10-24.
  10. Short.io pricing (API rate limit and link automation), Short.io, as published on 24 October 2026. Checked 2026-10-24.
  11. 429 Too Many Requests, MDN Web Docs, 2026-06-22. Checked 2026-10-23.

Questions people also ask

Is there a free URL shortener API?

Yes, several. As published on 24 October 2026, Bitly's Free plan allows 1,000 API requests a month, Rebrandly's 100 calls a minute with 10 links a month, and Short.io's 1,000 links by API or bulk. BN Shortener includes the full API on Free, with 100 new links a month and 1,000 requests a minute.

How do I get an API key for BN Shortener?

Sign up free at b1.lc, open Integrations > API (the API Portal) in the dashboard and create a key. It is shown once, so copy it into an environment variable straight away; BN stores only a hash of it.

Can I choose the back-half of the short link through the API?

Yes. Send custom_code in the create request, for example "spring-sale". Aliases are 3 to 50 characters of letters, digits, hyphens and underscores; a code that is already taken returns a 409 code-exists error.

Can I create short links on my own domain through the API?

Yes. Add the domain in the dashboard first (CNAME plus a TXT verification record), wait for its SSL certificate to become active, then send its name in the domain field. Domains cannot be added through the API; GET /api/v1/domains lists the ones you can use.

How do I get clicks into my own system without polling?

Create a webhook for link.clicked (or qr.scanned, link.converted and the other events). Deliveries are signed with an X-BN-Signature header and a GitHub-style X-Hub-Signature-256 header; the webhooks page in the docs explains how to verify them.

Is there an official SDK?

Yes. Python SDK: pip install bn-shortener (PyPI), which also installs the bn command line. TypeScript SDK: npm install @bn-shortner/shortener (npm, Node 20+, browsers, Workers). You can also call the API over plain HTTP.

Try it on your next link

The Free plan includes a custom domain, 5 dynamic QR codes, a bio page and click analytics. No credit card.