URL Shortener API: Shorten Links Programmatically (Code Examples)

J. Shams
May 13, 2026
45 mins read
URL Shortener API: Shorten Links Programmatically (Code Examples)

If you are building a product that generates links at scale, manually shortening URLs is not a workflow. You need a URL shortener API that handles authentication cleanly, returns predictable responses, and gives you full control over targeting, pixels, and analytics from your own codebase.

This guide walks you through every step: authentication, core endpoints, advanced parameters, and real code examples in JavaScript, Python, and PHP. You will also see how to wire it all into automation tools like n8n, Zapier, and WordPress hooks using The Automation Pipeline framework.

What Is a URL Shortener API and Why Do Developers Use It?

A URL shortener API is a REST interface that accepts a long URL and returns a short one, along with metadata like click stats, targeting rules, and pixel configurations. It removes the need for a dashboard entirely when your link creation is event-driven or high-volume.

Common use cases include:

  • Generating unique short links per user inside a SaaS app
  • Automating campaign link creation from a CRM or spreadsheet
  • Embedding short links in transactional emails without touching a UI
  • Syncing link performance data into a BI dashboard
  • Firing retargeting pixels on every click without modifying the destination page

A REST API link shortener does more than compress a URL. It gives your application the ability to create, configure, and measure links programmatically, turning every shortened link into a tracked, targetable asset owned by your system.

According to MDN's Fetch API documentation, the native browser Fetch API makes it straightforward to call REST endpoints without external dependencies. On the server side, the Python Requests library remains the most widely used HTTP client for Python developers, making it the natural choice for API integrations.

Authentication: Getting Your API Key

HitURL uses Bearer token authentication. Every request requires an Authorization header with your API key. You get your key from the HitURL developer dashboard after creating a free account.

Your base header block looks like this across all languages:

Authorization: Bearer YOUR_API_KEY
Content-Type: application/json
Accept: application/json

Store your API key in an environment variable, never hardcoded in source files. Use process.env.HITURL_API_KEY in Node.js or os.environ.get("HITURL_API_KEY") in Python.

Rate Limits and Error Handling

Before writing a single line of integration code, understand the limits. HitURL's API returns standard HTTP status codes and rate limit headers so your app can respond gracefully.

  • 429 Too Many Requests: You have hit the rate limit. Check the Retry-After header for the cooldown period.
  • 401 Unauthorized: Your API key is missing or invalid.
  • 422 Unprocessable Entity: The request body failed validation. Check the errors object in the response.
  • 404 Not Found: The link alias does not exist.
  • 500 Internal Server Error: Server-side issue. Implement exponential backoff and retry.

Always build your API integration to handle 429 responses with a retry loop using exponential backoff. A link shortener that fails silently in a CRM automation pipeline creates broken links in sent emails, and that damage is impossible to reverse.

A robust error handler in any language checks the HTTP status code first, parses the JSON error body second, and logs both before surfacing feedback to the user or triggering a retry.

Core Endpoint: Shorten a URL (JavaScript, Python, PHP)

The primary endpoint accepts a POST request with your long URL and optional configuration parameters. Here are production-ready examples in three languages.

JavaScript (Fetch API)

const shortenLink = async (longUrl, alias = null) => {
  const body = { url: longUrl };
  if (alias) body.alias = alias;

  const response = await fetch('https://hiturl.at/api/v1/links', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${process.env.HITURL_API_KEY}`,
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    },
    body: JSON.stringify(body)
  });

  if (!response.ok) {
    const error = await response.json();
    throw new Error(`API Error ${response.status}: ${JSON.stringify(error)}`);
  }

  return response.json();
};

// Usage
shortenLink('https://example.com/very-long-landing-page-url', 'my-campaign')
  .then(data => console.log(data.short_url))
  .catch(err => console.error(err));

Python (Requests Library)

import os
import requests

def shorten_url(long_url: str, alias: str = None) -> dict:
    headers = {
        "Authorization": f"Bearer {os.environ.get('HITURL_API_KEY')}",
        "Content-Type": "application/json",
        "Accept": "application/json"
    }
    payload = {"url": long_url}
    if alias:
        payload["alias"] = alias

    response = requests.post(
        "https://hiturl.at/api/v1/links",
        json=payload,
        headers=headers
    )
    response.raise_for_status()
    return response.json()

# Usage
result = shorten_url("https://example.com/product-page", alias="spring-sale")
print(result["short_url"])

PHP (cURL)

<?php
function shortenUrl(string $longUrl, string $alias = ''): array {
    $payload = ['url' => $longUrl];
    if ($alias) $payload['alias'] = $alias;

    $ch = curl_init('https://hiturl.at/api/v1/links');
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => json_encode($payload),
        CURLOPT_HTTPHEADER     => [
            'Authorization: Bearer ' . getenv('HITURL_API_KEY'),
            'Content-Type: application/json',
            'Accept: application/json'
        ]
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode !== 201) {
        throw new RuntimeException("API Error $httpCode: $response");
    }

    return json_decode($response, true);
}

$link = shortenUrl('https://example.com/checkout', 'checkout-link');
echo $link['short_url'];

Each of these returns a JSON object containing the short_url, alias, created_at timestamp, and the link ID you will need for stats and update calls.

Get Stats, Update, and Delete a Link

Your link ID unlocks the full management lifecycle. These three endpoints cover the most common post-creation operations.

Get Click Stats (Python)

def get_link_stats(link_id: str) -> dict:
    headers = {
        "Authorization": f"Bearer {os.environ.get('HITURL_API_KEY')}",
        "Accept": "application/json"
    }
    response = requests.get(
        f"https://hiturl.at/api/v1/links/{link_id}/stats",
        headers=headers
    )
    response.raise_for_status()
    return response.json()

stats = get_link_stats("abc123")
print(f"Total clicks: {stats['total_clicks']}")
print(f"Unique clicks: {stats['unique_clicks']}")

Update a Link (JavaScript)

const updateLink = async (linkId, updates) => {
  const response = await fetch(`https://hiturl.at/api/v1/links/${linkId}`, {
    method: 'PATCH',
    headers: {
      'Authorization': `Bearer ${process.env.HITURL_API_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(updates)
  });
  if (!response.ok) throw new Error(`Update failed: ${response.status}`);
  return response.json();
};

// Change the destination URL without breaking the short link
await updateLink('abc123', { url: 'https://example.com/new-landing-page' });

Delete a Link (PHP)

<?php
function deleteLink(string $linkId): bool {
    $ch = curl_init("https://hiturl.at/api/v1/links/$linkId");
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CUSTOMREQUEST  => 'DELETE',
        CURLOPT_HTTPHEADER     => [
            'Authorization: Bearer ' . getenv('HITURL_API_KEY')
        ]
    ]);
    curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return $httpCode === 204;
}

See how HitURL tracks every click, fires your pixels, and generates QR codes: create your free account at hiturl.at and start calling the API today.

Advanced Parameters: Geo Targeting, Device Targeting, Pixels, and Campaigns

This is where the API moves beyond simple link compression. HitURL lets you pass targeting rules and pixel configurations directly in the POST body when you create or update a link.

Passing geo targeting rules through the API means every link your application generates can route users to a country-specific landing page without any manual dashboard configuration. Your automation logic sets the rules; the redirect engine executes them at click time.

Here is a full advanced payload example in Python that assigns a Facebook pixel, sets geo targeting, and assigns the link to a campaign:

advanced_payload = {
    "url": "https://example.com/global-sale",
    "alias": "global-sale-q4",
    "campaign_id": "camp_789xyz",
    "pixels": [
        {"type": "facebook", "pixel_id": "1234567890"}
    ],
    "geo_targeting": [
        {"country": "US", "url": "https://example.com/us-sale"},
        {"country": "GB", "url": "https://example.com/uk-sale"},
        {"country": "DE", "url": "https://example.com/de-sale"}
    ],
    "device_targeting": [
        {"device": "ios", "url": "https://apps.apple.com/app/your-app"},
        {"device": "android", "url": "https://play.google.com/store/apps/your-app"}
    ]
}

response = requests.post(
    "https://hiturl.at/api/v1/links",
    json=advanced_payload,
    headers=headers
)
response.raise_for_status()
result = response.json()
print(result["short_url"])

For a deeper look at how geo targeting rules work at the redirect level, see the guide on redirecting links by country with geo targeting. For pixel configuration strategy, the articles on adding a Facebook pixel to your short links and connecting Google Tag Manager to your URL shortener cover the setup in detail.

The Automation Pipeline Framework

The Automation Pipeline is a three-stage framework for building link creation workflows that run without manual intervention. It breaks down every integration into three phases: Trigger, Transform, Deliver.

  • Trigger: Something in your system fires the link creation request. A new contact in your CRM, a published blog post, a completed form submission, or a scheduled job.
  • Transform: Your code or automation tool calls the shorten URL API, enriches the payload with targeting rules, pixel IDs, and campaign assignments, and captures the returned short URL.
  • Deliver: The short URL is written back to its destination: a CRM field, an email template variable, a database row, a Slack message, or a spreadsheet cell.

The Automation Pipeline framework keeps link creation logic separate from link consumption. The system that creates the link does not need to know where it ends up. The system that uses the link does not need to know how it was created. That separation makes integrations easier to debug and scale independently.

n8n Integration

In n8n, use an HTTP Request node with the POST method, point it at https://hiturl.at/api/v1/links, and set your API key as a header credential. Pass the long URL from a preceding node using an expression like {{ $json["destination_url"] }}. Wire the output to a CRM Update node to write the short URL back to the contact record.

Zapier Integration

Use Zapier's Webhooks by Zapier action. Set the method to POST, the URL to the HitURL API endpoint, and add your Bearer token as a custom header. Map the long URL field from your trigger app. The returned short_url field becomes available for all subsequent Zap steps.

WordPress Hook

Fire an API call inside a WordPress save_post hook to auto-shorten every published post's permalink. Store the returned short URL in post meta. Display it in your share buttons without ever opening the HitURL dashboard.

add_action('save_post', function($post_id) {
    if (wp_is_post_revision($post_id) || get_post_status($post_id) !== 'publish') return;

    $permalink = get_permalink($post_id);
    $response  = wp_remote_post('https://hiturl.at/api/v1/links', [
        'headers' => [
            'Authorization' => 'Bearer ' . getenv('HITURL_API_KEY'),
            'Content-Type'  => 'application/json'
        ],
        'body' => json_encode(['url' => $permalink])
    ]);

    if (!is_wp_error($response)) {
        $data = json_decode(wp_remote_retrieve_body($response), true);
        update_post_meta($post_id, '_short_url', $data['short_url']);
    }
});

CRM Enrichment and Team Workflows

The stats endpoint is as valuable as the creation endpoint for CRM use cases. Pull click data on a schedule and write it back to contact records: total clicks, unique clicks, top countries, and device breakdown. Sales teams see engagement without leaving the CRM.

If your team manages links across multiple campaigns and brands, the link management guide for teams covers how to structure campaigns and permissions at the account level before wiring them into API automation. And if you are setting up a custom domain for your short links, the guide on branded short links with a custom domain walks through the DNS configuration you need first.

The HitURL pricing page shows the API call limits per plan so you can size your integration before you go to production.

FAQ: URL Shortener API

Do I need a paid plan to use the HitURL API?

No. The API is available on the free tier. You get a set number of API calls per month at no cost, which is enough to build and test your integration.

Can I create links with custom aliases via the API?

Yes. Pass the alias parameter in your POST request body. If the alias is already taken, the API returns a 422 error with a clear message. Generate a unique fallback alias in your code if the preferred one fails.

How do I attach a retargeting pixel to an API-created link?

Include a pixels array in your POST body with the pixel type and ID. Supported types include Facebook, Google, LinkedIn, Twitter, AdRoll, Quora, and GTM. The pixel fires on every click through the short link without any changes to your destination page.

What is the rate limit for the HitURL API?

Rate limits depend on your plan tier. All plans return a X-RateLimit-Remaining header on every response so your application knows how many calls remain in the current window. Build a check for this header into your integration loop.

Can the API update a link after it has been created?

Yes. Use a PATCH request to the /api/v1/links/{id} endpoint. You can update the destination URL, targeting rules, pixel assignments, or campaign without changing the short URL alias. This is the right approach for evergreen links that point to seasonal content.

Start Building Today

You now have working code in three languages, a clear error handling strategy, advanced targeting parameters, and a framework for wiring it all into your automation stack. The HitURL REST API gives you full programmatic control over every link your application creates.

The best link integrations are invisible to the end user. They get a clean short URL in the right channel at the right time, routed to the right destination. The API makes that happen at any scale, on any trigger, without anyone touching a dashboard.

See how HitURL tracks every click, fires your pixels, and generates QR codes: free at hiturl.at. Create your free account and get your API key in under two minutes.

Author

Sigue leyendo

Más publicaciones de nuestro blog

O que é um encurtador de URL? Guia completo 2026
By J. Shams May 13, 2026
Um link longo afasta cliques. Um link curto convida. Você já recebeu um link no WhatsApp com 200 caracteres cheios de parâmetros, interrogações...
Leer más
Cómo rastrear clics en enlaces con parámetros UTM (guía práctica)
By J. Shams May 12, 2026
Tu campaña tuvo miles de clics. Pero no sabes de dónde vienen. Lanzaste un anuncio en Facebook, enviaste un mensaje por WhatsApp y publicaste en...
Leer más
How to Set Up Facebook Pixel Retargeting Through a Short Link
By J. Shams May 12, 2026
You're running cold traffic to a landing page. The visitor clicks your link, bounces before the page fully loads, and your Facebook Pixel never fires....
Leer más