URL Shortener API Guide: Automate Links Like a Pro
You run a website, SaaS product, or marketing operation and need to generate, manage, and track short links programmatically — without logging into a dashboard every time. A URL shortener API turns that into a few lines of code.
What a URL Shortener API Does
A URL shortener API is an HTTP-based interface that lets your application create short links, retrieve analytics, manage link metadata, and configure settings — all over RESTful endpoints. Instead of copying and pasting URLs into a web form, you send a POST request with the long URL and get back a shortened link as structured JSON. Every operation available in the dashboard — creating, editing, deleting, tagging, and reporting — is exposed through the API.
The typical flow works like this: your backend receives a long URL from a user or an automated process, sends it to the shortener API, receives the short code or slug in response, and stores or returns it. The entire round trip takes under 100 milliseconds on a well-optimized service. Because the API is stateless and transport-agnostic, you can call it from any language or platform that supports HTTP — Node.js, Python, Ruby, PHP, Go, or even cURL from a shell script.
Behind the scenes, the API accepts your long URL, validates it, checks for duplicates or custom alias conflicts, writes the mapping to a database, and returns the generated short code. Premium services also let you specify custom slugs, set expiration dates, attach UTM parameters, assign tags, and choose which domain the short link uses — all within a single API call.
Common Use Cases
A URL shortener API becomes most valuable when it's integrated into an existing workflow. Here are the scenarios where developers reach for the API instead of the dashboard:
Auto-Shorten Blog Post URLs on Publish
Content management systems like WordPress, Ghost, or custom headless CMS setups can fire an API call on the post_publish hook. The CMS sends the canonical URL to the shortener API, receives a short link, and stores it as a custom field. When the article renders on social media or email digests, the short link is ready to use. This eliminates the manual step of copying the URL, visiting the shortener, and pasting it back.
Create Tracking Links from CRM
Sales and marketing teams using platforms like HubSpot, Salesforce, or Pipedrive can generate tracked short links directly from the CRM interface. A Zapier webhook or custom integration watches for new deals or campaigns and calls the shortener API with pre-configured UTM parameters. Every link generated this way is automatically tagged with the campaign name, source, and medium, so analytics are consistent across the entire team.
Bulk Generate Links from CSV
When you need to create hundreds or thousands of short links — say, for a product catalog with individual SKU tracking — clicking a "Create" button in a dashboard is not feasible. A short script reads a CSV file with columns for the destination URL, custom alias, tags, and UTM parameters, iterates over each row, and calls the API's bulk creation endpoint. In under a minute, the entire catalog has trackable short links.
Dynamic QR Codes
QR codes printed on flyers, menus, or packaging link to a short URL. When you use a shortener API, the destination URL is editable even after the QR code is printed. Your application can update the long URL through the API without changing the short code or regenerating the QR image. This is especially useful for event signage where the registration link might change, or for restaurant menus where items rotate seasonally.
Authentication
Every API request to a URL shortener service must be authenticated. The three most common methods are API keys passed as headers, bearer tokens (JWT-based), and HTTP Basic Auth for legacy integrations.
API keys are the simplest approach: you generate a key from the service dashboard and include it in every request header. Most modern shorteners (Urlvy, Bitly, Short.io) expect the key in the Authorization header as Bearer <token>. Basic Auth using the API key as the username and an empty password is still supported by some providers but is being phased out in favor of bearer tokens.
# Basic authentication — deprecated but still seen
curl -u "YOUR_API_KEY:" \
https://api.urlvy.com/v1/shorten \
-d '{"url": "https://example.com/long-page"}'
The preferred modern approach uses the bearer token pattern, which is more secure and standard across the industry:
curl -X POST https://api.urlvy.com/v1/shorten \
-H "Authorization: Bearer urlvy_live_abc123def456" \
-H "Content-Type: application/json" \
-d '{"url": "https://example.com/long-page"}'
Tokens should be scoped to the minimum permissions needed. A CI/CD pipeline that only creates links does not need a token that can delete links or view billing details. Urlvy and most modern services support scoped API keys that you can restrict to specific operations and even to specific domains.
Creating a Short Link via API
Creating a short link is the most fundamental API operation. You send the long URL to the creation endpoint, optionally include custom parameters, and receive the shortened link in the response. Here is a complete cURL example with all the common options:
curl -X POST https://api.urlvy.com/v1/shorten \
-H "Authorization: Bearer urlvy_live_abc123def456" \
-H "Content-Type: application/json" \
-d '{
"url": "https://example.com/very-long-blog-post-title-that-needs-shortening",
"domain": "urlvy.co",
"slug": "blog-guide-2026",
"tags": ["blog", "guide", "2026"],
"utm_source": "twitter",
"utm_medium": "social",
"utm_campaign": "api_guide_launch"
}'
The JSON response typically includes the short URL, the slug, the original URL, and metadata:
{
"id": "lnk_9a8b7c6d5e",
"short_url": "https://urlvy.co/blog-guide-2026",
"slug": "blog-guide-2026",
"long_url": "https://example.com/very-long-blog-post-title-that-needs-shortening",
"domain": "urlvy.co",
"tags": ["blog", "guide", "2026"],
"clicks": 0,
"created_at": "2026-06-28T14:30:00Z",
"updated_at": "2026-06-28T14:30:00Z",
"utm": {
"source": "twitter",
"medium": "social",
"campaign": "api_guide_launch"
}
}
If you are integrating from a Node.js backend, the same operation using fetch looks like this:
const API_TOKEN = process.env.URLVY_API_TOKEN;
async function createShortLink(longUrl, options = {}) {
const response = await fetch("https://api.urlvy.com/v1/shorten", {
method: "POST",
headers: {
"Authorization": `Bearer ${API_TOKEN}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
url: longUrl,
domain: options.domain || "urlvy.co",
slug: options.slug,
tags: options.tags || [],
utm_source: options.utmSource,
utm_medium: options.utmMedium,
utm_campaign: options.utmCampaign,
}),
});
if (!response.ok) {
const error = await response.json();
throw new Error(`Urlvy API error: ${error.message}`);
}
return response.json();
}
// Usage
const link = await createShortLink(
"https://example.com/very-long-blog-post-title",
{ slug: "blog-guide", tags: ["blog"], utmSource: "twitter" }
);
console.log(link.short_url); // https://urlvy.co/blog-guide
Error responses follow standard HTTP status codes. A 400 means a bad request — the URL is invalid or a required field is missing. A 409 indicates a slug conflict — the custom alias you requested is already taken. A 429 means you have hit your rate limit and should back off. Always check the error body for a human-readable message and a machine-parseable error code.
Bulk Operations
Creating links one at a time works for small volumes, but when you need to generate hundreds or thousands of links, bulk endpoints are far more efficient. They reduce HTTP overhead, allow atomic batch validation, and typically return results in a single response.
Here is a bulk creation request that shortens five URLs in a single API call:
curl -X POST https://api.urlvy.com/v1/batch/shorten \
-H "Authorization: Bearer urlvy_live_abc123def456" \
-H "Content-Type: application/json" \
-d '{
"links": [
{ "url": "https://example.com/product/alpha", "slug": "alpha-2026", "tags": ["product"] },
{ "url": "https://example.com/product/beta", "slug": "beta-2026", "tags": ["product"] },
{ "url": "https://example.com/product/gamma", "slug": "gamma-2026", "tags": ["product"] },
{ "url": "https://example.com/product/delta", "slug": "delta-2026", "tags": ["product"] },
{ "url": "https://example.com/product/epsilon", "slug": "epsilon-2026", "tags": ["product"] }
]
}'
The bulk response returns an array of results in the same order as the request, with individual status codes so you can handle partial failures:
{
"results": [
{ "status": 201, "short_url": "https://urlvy.co/alpha-2026", "slug": "alpha-2026" },
{ "status": 201, "short_url": "https://urlvy.co/beta-2026", "slug": "beta-2026" },
{ "status": 409, "error": "Slug 'gamma-2026' already exists", "slug": "gamma-2026" },
{ "status": 201, "short_url": "https://urlvy.co/delta-2026", "slug": "delta-2026" },
{ "status": 201, "short_url": "https://urlvy.co/epsilon-2026", "slug": "epsilon-2026" }
],
"total_requests": 5,
"succeeded": 4,
"failed": 1
}
Most services impose a batch size limit — typically 100 to 500 links per request. For larger workloads, paginate your batches and add a small delay between requests to stay within rate limits. The bulk endpoint is ideal for migrations, catalog imports, and syncing data from external systems.
Retrieving Analytics via API
Creating links is only half the story. The API also exposes click data, geographic breakdowns, referrer information, and time-series charts so you can build custom dashboards or pipe data into your existing analytics stack.
Fetching click data for a specific link is a simple GET to the link's analytics endpoint:
curl https://api.urlvy.com/v1/links/lnk_9a8b7c6d5e/analytics \
-H "Authorization: Bearer urlvy_live_abc123def456" \
-H "Content-Type: application/json"
The response contains comprehensive click data broken down by dimension:
{
"link_id": "lnk_9a8b7c6d5e",
"short_url": "https://urlvy.co/blog-guide-2026",
"total_clicks": 1247,
"unique_clicks": 892,
"period": {
"start": "2026-01-01T00:00:00Z",
"end": "2026-06-28T23:59:59Z"
},
"clicks_over_time": [
{ "date": "2026-06-01", "clicks": 42 },
{ "date": "2026-06-02", "clicks": 38 },
{ "date": "2026-06-03", "clicks": 55 }
],
"top_referrers": [
{ "source": "twitter.com", "clicks": 412, "percentage": 33.0 },
{ "source": "linkedin.com", "clicks": 289, "percentage": 23.2 },
{ "source": "Direct / Unknown", "clicks": 198, "percentage": 15.9 }
],
"top_countries": [
{ "country": "United States", "clicks": 487, "percentage": 39.1 },
{ "country": "United Kingdom", "clicks": 203, "percentage": 16.3 },
{ "country": "Germany", "clicks": 142, "percentage": 11.4 }
],
"top_browsers": [
{ "browser": "Chrome", "clicks": 698, "percentage": 56.0 },
{ "browser": "Safari", "clicks": 321, "percentage": 25.7 },
{ "browser": "Firefox", "clicks": 112, "percentage": 9.0 }
],
"device_breakdown": {
"desktop": { "clicks": 524, "percentage": 42.0 },
"mobile": { "clicks": 648, "percentage": 52.0 },
"tablet": { "clicks": 75, "percentage": 6.0 }
}
}
You can also aggregate analytics across multiple links by tag, domain, or date range. This lets you build a team dashboard showing total clicks, top-performing content, and traffic trends without ever logging into the shortener's UI. Many developers combine this data with Google Analytics or Mixpanel by exporting click events via webhook — more on that in the next section.
Webhooks for Real-Time Events
Polling the analytics endpoint on a schedule works, but webhooks are more efficient. A webhook is an HTTP callback — your server exposes an endpoint, and the URL shortener sends a POST request to it every time a tracked event occurs (like a click or a conversion).
Configuring a webhook in Urlvy is straightforward. You register your endpoint URL in the dashboard or via the API, choose which events to subscribe to, and Urlvy delivers a JSON payload every time the event fires:
curl -X POST https://api.urlvy.com/v1/webhooks \
-H "Authorization: Bearer urlvy_live_abc123def456" \
-H "Content-Type: application/json" \
-d '{
"url": "https://your-server.com/webhooks/urlvy",
"events": ["link.click", "link.created"],
"secret": "whsec_your_webhook_secret"
}'
The payload delivered to your webhook endpoint looks like this:
{
"event": "link.click",
"timestamp": "2026-06-28T15:01:23Z",
"data": {
"link_id": "lnk_9a8b7c6d5e",
"short_url": "https://urlvy.co/blog-guide-2026",
"long_url": "https://example.com/very-long-blog-post-title",
"clicker": {
"ip": "203.0.113.42",
"user_agent": "Mozilla/5.0 ... Chrome/126.0.0.0",
"referrer": "https://twitter.com/someuser/status/123456",
"country": "US",
"device": "mobile"
}
}
}
To ensure authenticity, the webhook payload is signed with your secret using HMAC-SHA256. Your server should verify the signature in the X-Urlvy-Signature header before processing the payload. This prevents attackers from sending fake click events to your endpoint:
import { createHmac, timingSafeEqual } from "node:crypto";
const WEBHOOK_SECRET = process.env.URLVY_WEBHOOK_SECRET;
export async function handleWebhook(request) {
const signature = request.headers.get("X-Urlvy-Signature");
const body = await request.text();
const expectedSig = createHmac("sha256", WEBHOOK_SECRET)
.update(body)
.digest("hex");
const actual = Buffer.from(signature);
const expected = Buffer.from(expectedSig);
if (actual.length !== expected.length ||
!timingSafeEqual(actual, expected)) {
return new Response("Invalid signature", { status: 401 });
}
const event = JSON.parse(body);
console.log(`Link clicked: ${event.data.short_url}`);
return new Response("OK", { status: 200 });
}
Webhooks are invaluable for real-time use cases: updating a live dashboard, firing a Slack notification when a high-value link is clicked, logging conversions to your data warehouse, or triggering a follow-up email sequence. They reduce latency from minutes (polling interval) to milliseconds, and they offload the polling overhead from your infrastructure.
API Comparison Checklist
Not all URL shortener APIs are created equal. When evaluating a provider, here are the criteria that matter for a developer experience:
- Rate limits. What is the maximum number of requests per minute or per hour? Is the limit per API key or per account? Are there burst allowances? Can you request a higher limit?
- Uptime SLA. Does the provider publish an uptime guarantee? Is there a status page? What is the historical uptime? A short link service that goes down means your links stop resolving.
- Documentation quality. Is the API reference complete with request/response examples? Are there guides for common use cases? Is there an OpenAPI/Swagger spec you can import into Postman?
- SDK availability. Does the provider maintain official SDKs for Node.js, Python, Ruby, and Go? Are there community SDKs? Is the API so clean that you do not need an SDK?
- Webhook support. Can you subscribe to click events in real time? Are webhook signatures supported? Is the retry policy documented?
- Custom domains. Can you use your own branded domain for short links? Is domain configuration available through the API or only in the dashboard?
- Data retention. How long are click logs kept? Can you export historical data? Is there a data deletion policy for GDPR compliance?
- Team features. Can you create scoped API keys per team member? Are there audit logs for API usage? Can roles and permissions be managed programmatically?
Urlvy vs Bitly vs Short.io: API Feature Comparison
Here is how the three major URL shortener APIs stack up against each other on the features developers care about most:
| Feature | Urlvy | Bitly | Short.io |
|---|---|---|---|
| RESTful API | ? v1 | ? v4 | ? v2 |
| Rate limit | 1,000 req/min | 50 req/min (free) | 600 req/min |
| Bulk creation | ? Up to 500 | ? No | ? Up to 100 |
| Webhooks | ? Signed HMAC | ? Enterprise only | ? Signed HMAC |
| Custom domains | ? All plans | ? Paid plans | ? Paid plans |
| Free tier API | 500 links, no CC | 50 links, CC required | 100 links, no CC |
| OpenAPI spec | ? Yes | ? Yes | ? No |
| SDK (Node.js) | ? Official | ? Official | ? Community |
| Analytics API | Clicks, geo, referrer | Clicks, geo (paid) | Clicks, referrer |
| Uptime SLA | 99.9% | 99.9% (paid) | 99.5% |
Security Best Practices
A leaked API key can be used to create arbitrary short links that point to phishing pages, spam destinations, or malicious downloads — damaging your brand reputation and getting your short domains blacklisted. Follow these practices to keep your API credentials safe:
- Store API keys securely. Use environment variables or a secrets manager like AWS Secrets Manager, HashiCorp Vault, or Doppler. Never hardcode keys in source code, configuration files, or client-side JavaScript bundles.
- Use HTTPS exclusively. All API communication must happen over TLS. The bearer token is transmitted in the Authorization header, and without HTTPS it can be intercepted in plain text. Most services reject HTTP requests by default.
- Rotate keys regularly. Generate new API keys every 90 days and invalidate the old ones. Automation tools like GitHub Actions or cron-based scripts can rotate keys on a schedule and update the secrets in your deployment environment.
- Scope keys to minimum permissions. If a key only needs to create links, do not give it delete or billing permissions. Urlvy supports granular scopes — use them. A compromised limited key is far less damaging than a full-access key.
- Validate destination URLs server-side. If your application lets users submit URLs that get shortened, validate them against an allowlist of approved domains. This prevents your shortener from being used as an open redirect by bad actors.
- Monitor API usage. Set up alerts for unusual patterns — a sudden spike in creation requests or clicks from unexpected geographic regions. Most shortener dashboards provide usage logs; pipe them into your SIEM or monitoring system.
- Use webhook secrets. Always verify the HMAC signature on incoming webhook payloads. Without verification, an attacker can forge click events or send malicious data to your endpoint.
Summary
A URL shortener API turns link management from a manual dashboard chore into a programmable part of your infrastructure. Whether you are auto-generating short links when blog posts go live, bulk-importing a product catalog, piping click analytics into a custom dashboard, or reacting to clicks in real time via webhooks, the API is the tool that makes it all possible.
- RESTful APIs with bearer token authentication are the industry standard — stateless, language-agnostic, and simple to integrate.
- Bulk endpoints handle hundreds of links in a single request, ideal for migrations and catalog imports.
- Analytics endpoints expose click data broken down by time, geography, referrer, device, and browser — enough data to build a full reporting layer.
- Webhooks deliver real-time click notifications with HMAC-signed payloads so you can trust the source.
- For more on the mechanics of URL shortening, read how short URLs work. To dive deeper into tracking, see our URL shortener analytics guide.
Urlvy launches soon — join the VIP Beta
Get 100% free access to URL shortener, QR codes, and file sharing. Early beta testers get exclusive Lifetime Deal pricing.
Join the VIP Beta →