How to Bulk Generate Short Links Programmatically via API with JSON

Muhammad Jahangeer
June 27, 2026
40 minutos de lectura
How to Bulk Generate Short Links Programmatically via API with JSON

Why Developers Need a Bulk Shorten URLs API

If you are generating thousands of short links for a product catalog, an email campaign, or a data pipeline, doing it one request at a time is not a workflow. It is a bottleneck. A bulk shorten URLs API lets you send an array of destination URLs in a single JSON payload and get back a mapped list of short links in one response.

This guide walks you through exactly how to do that with HitURL's API: how to structure the request body, handle pagination and rate limits, and store the output efficiently in your database. By the end, you have a repeatable pattern you can drop into any stack.

The single-request rule: Any batch link generation workflow that requires more than one HTTP call per URL is not a bulk API. True bulk shortening sends N URLs in one payload and receives N short links in one response. Anything else multiplies your latency by N.

Before You Start: Authentication and Base Setup

Every request to the HitURL REST API requires a Bearer token. You generate one from your account dashboard. Include it in the Authorization header of every request.

The base URL for all API calls is https://hiturl.at/api/v1. All request and response bodies use application/json. Review the full HitURL API documentation for endpoint references, available parameters, and authentication details before writing your first line of code.

You also need to decide, upfront, whether your short links require custom aliases, retargeting pixels, or geo targeting. Adding those fields per URL is supported in the bulk endpoint, and it is far cheaper to configure them at creation time than to patch each link afterward.

How to Structure Your JSON Payload for Batch Link Shortening

The bulk endpoint accepts a top-level urls array. Each element in the array is an object describing one link. At minimum, each object needs a destination field. Optional fields include alias, title, domain, pixel_ids, and geo_rules.

Here is a minimal payload for batch shortening three URLs:

POST /api/v1/links/bulk
Authorization: Bearer YOUR_API_TOKEN
Content-Type: application/json

{
  "urls": [
    { "destination": "https://example.com/product/red-shoes", "title": "Red Shoes PDP" },
    { "destination": "https://example.com/product/blue-jacket", "title": "Blue Jacket PDP" },
    { "destination": "https://example.com/blog/summer-trends", "title": "Summer Trends Post" }
  ]
}

The response returns an array in the same order as the input, with each object containing the original destination, the generated short_url, the assigned id, and a status field indicating success or failure for that individual item. Order preservation is critical: it is what lets you map outputs back to your source records without a secondary lookup.

Always preserve array order. A well-designed bulk link API returns results in the same sequence as the input array. This one-to-one positional mapping eliminates the need for a separate lookup step when writing short URLs back to your database rows.

A Production-Ready Bulk Shortening Pattern in JavaScript

The following pattern uses the Fetch API to send a batch request and write the results back to a local array. Adapt it to your runtime, whether that is Node.js, Deno, or a browser-based tool.

const API_TOKEN = process.env.HITURL_API_TOKEN;
const BASE_URL = 'https://hiturl.at/api/v1';

async function bulkShortenUrls(urlObjects) {
  const response = await fetch(`${BASE_URL}/links/bulk`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${API_TOKEN}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ urls: urlObjects })
  });

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

  return response.json();
}

// Example usage
const inputUrls = [
  { destination: 'https://example.com/page-1', title: 'Page 1' },
  { destination: 'https://example.com/page-2', title: 'Page 2' }
];

bulkShortenUrls(inputUrls).then(data => {
  data.results.forEach((result, index) => {
    if (result.status === 'success') {
      inputUrls[index].shortUrl = result.short_url;
      inputUrls[index].linkId   = result.id;
    } else {
      console.error(`Failed for index ${index}:`, result.error);
    }
  });
  console.log(inputUrls);
});

Notice the per-item status check inside the loop. A bulk response can have a 200 HTTP status while individual items inside the array have failed. Always check at the item level, not the request level.

For more patterns across different languages and runtimes, see the HitURL API code examples covering Python, PHP, and cURL.

Switch to HitURL today. Free to start, and you keep every feature that matters. Create your account at hiturl.at.

How Do You Handle API Rate Limits When Shortening URLs in Bulk?

Rate limits exist to protect API infrastructure. HitURL enforces limits at the account tier level. Check your current limits in the HitURL pricing page to understand the batch size and per-minute call caps for your plan.

The standard approach for working within rate limits is The Chunked Retry Method, a three-step pattern:

  1. Chunk your input array. Split your full URL list into batches that respect the maximum items-per-request limit. A batch size of 100 to 500 is typical for most bulk shortening APIs.
  2. Implement exponential backoff. If you receive a 429 Too Many Requests response, wait before retrying. Start at 1 second, double on each subsequent failure, and cap at 60 seconds. Include a maximum retry count (three to five attempts) before logging the batch as failed.
  3. Track which batches succeeded. Maintain a queue of pending batches. On a successful response, mark that chunk as processed and persist the results. On a permanent failure (after all retries), isolate that chunk for manual review rather than blocking the entire job.
async function bulkShortenWithRetry(urlObjects, batchSize = 200, maxRetries = 4) {
  const results = [];
  for (let i = 0; i < urlObjects.length; i += batchSize) {
    const chunk = urlObjects.slice(i, i + batchSize);
    let attempt = 0;
    let delay = 1000;
    while (attempt < maxRetries) {
      try {
        const data = await bulkShortenUrls(chunk);
        results.push(...data.results);
        break;
      } catch (err) {
        if (attempt === maxRetries - 1) throw err;
        await new Promise(res => setTimeout(res, delay));
        delay *= 2;
        attempt++;
      }
    }
  }
  return results;
}
The Chunked Retry Method is the production standard for bulk API workflows: split your input into fixed-size batches, apply exponential backoff on 429 errors, and persist each successful chunk independently. This prevents a single rate-limit hit from voiding an entire batch job.

Mapping Short Link Outputs Back to Your Database

Getting the short URLs back is only half the job. Writing them to your database cleanly is the other half. The recommended approach is a two-column extension on whatever table holds your source records: one column for the short URL string, one column for the HitURL link ID.

The link ID matters. It is what you use to update the destination URL later, pull click analytics via the API, or delete the link. Storing the string alone leaves you with a dead reference if you ever need to manage the link programmatically.

Here is a simple mapping pattern assuming your source records are in a JavaScript array:

// After calling bulkShortenWithRetry:
results.forEach((result, index) => {
  if (result.status === 'success') {
    sourceRecords[index].shortUrl = result.short_url;
    sourceRecords[index].hitUrlId  = result.id;
  }
});

// Then upsert sourceRecords into your DB in one batch write.
// Example with a hypothetical DB client:
await db.batchUpsert('products', sourceRecords, { conflictKey: 'product_id' });

If your source data comes from a spreadsheet, a CMS, or a no-code tool, you can automate the entire pipeline. The n8n URL shortener automation workflow guide shows how to connect HitURL's API to spreadsheets and databases without writing custom backend code.

Adding Retargeting Pixels and Geo Rules to Bulk Links

One of the advantages of generating links programmatically is that you can attach metadata to each URL at creation time. HitURL supports retargeting pixels (Facebook, Google, LinkedIn, Twitter, AdRoll, Quora, and Google Tag Manager) and geo plus device targeting rules, all configurable per link in the bulk payload.

To attach a pixel, include a pixel_ids array in the URL object. Pixel IDs are the numeric or string identifiers you set up once in your HitURL account under the Pixels section:

{
  "destination": "https://example.com/landing",
  "title": "Q3 Campaign Landing",
  "pixel_ids": ["fb_12345678", "gtm_GTM-XXXXX"]
}

For geo targeting, include a geo_rules array. Each rule specifies a country code and an alternate destination. Visitors from that country are redirected to the alternate URL. All other visitors go to the primary destination.

When you are managing bulk link campaigns across a team, consistent pixel and geo configuration is critical. The link management for teams guide covers how to set shared pixel libraries and permission structures so every team member's links fire the right tracking on click.

What Is the Right Batch Size for a Bulk URL Shortening API?

Batch size depends on two variables: the API's per-request item limit and your error tolerance. Larger batches mean fewer HTTP round trips, which is faster. Smaller batches mean a failure affects fewer records, which is safer.

A batch size of 100 to 200 URLs per request is a practical default for most production use cases. It balances throughput against the cost of retrying a failed chunk. If your use case involves very large datasets (50,000 URLs or more), consider processing in parallel streams with separate retry queues rather than a single sequential loop.

A batch size of 100 to 200 URLs per API request is the practical default for production bulk shortening jobs. It minimizes round-trip overhead while keeping the retry cost low if an individual chunk fails due to a rate limit or transient server error.

According to MDN's Fetch API documentation, fetch requests in browser environments are subject to CORS and connection limits. For bulk operations at scale, always run batch jobs from a server-side environment, not a browser client.

According to HitURL's own usage data, developers who switch from single-link API calls to batch requests reduce their total link-generation time by more than 90% on datasets above 1,000 URLs.

FAQ: Bulk URL Shortening via API

What is the maximum number of URLs I can send in a single bulk API request?

The item limit per request depends on your HitURL plan. Check the pricing page for per-tier limits. As a general rule, batch your input into chunks of 200 or fewer and use the Chunked Retry Method for any dataset larger than that limit.

Does the bulk API preserve the order of the input array in the response?

Yes. The HitURL bulk endpoint returns results in the same order as the input array. This means you can use positional indexing to map each short URL back to its source record without needing a secondary lookup by destination URL.

How do I handle partial failures in a bulk response?

A 200 HTTP response from the bulk endpoint does not guarantee all items succeeded. Check the status field on each item in the response array. Items with a status of error include an error field with details. Collect failed items, correct the issue (invalid URL, duplicate alias, etc.), and resubmit them as a new batch.

Can I attach custom aliases to links in a bulk request?

Yes. Include an alias field in each URL object. Aliases must be unique across your account. If two items in the same batch share an alias, the second one fails. Validate for alias uniqueness in your application before sending the request.

Is the HitURL bulk API available on the free plan?

The REST API is available across HitURL plans. Free accounts have access to core API functionality including bulk shortening. Higher-tier plans increase rate limits and batch size caps. See the full breakdown on the HitURL pricing page.

Start Generating Links at Scale

Batch link generation is not a nice-to-have for developers working with large datasets. It is the only workflow that scales. The pattern is consistent: structure your JSON payload, send one request per chunk, handle the status field at the item level, and persist both the short URL and the link ID back to your source records.

HitURL's bulk API gives you all of that, plus retargeting pixels, geo targeting, and branded QR codes on every link you create. It is free to start, and the features that matter to developers, including the full REST API, are available from day one.

Switch to HitURL today. Free to start, and you keep every feature that matters. Create your free account at hiturl.at and run your first bulk shortening job in under ten minutes.

Author

Muhammad Jahangeer
Muhammad Jahangeer
Muhammad Jahangeer is a Full-Stack Developer and digital entrepreneur with over 12 years of experience building web applications and online tools. Through the HitUrl Blog, he shares practical insights on QR codes, link management, digital marketing, and automation. HitUrl publishes content in English, Spanish, and Portuguese, helping users worldwide leverage simple tools to enhance their online presence.

Sigue leyendo

Más publicaciones de nuestro blog

¿Qué es el Link Rot? Cómo evitar que tus enlaces viejos mueran
Por Muhammad Jahangeer July 09, 2026
El 25% de los enlaces en sitios de noticias se rompen después de 7 años, según un análisis del New York Times citado en Wikipedia. Si administras...
Leer más
The API First URL Shortener: Automating Content Distribution at Scale
Por Muhammad Jahangeer July 09, 2026
Why Scaling SaaS Platforms Are Rebuilding Their Link LayerYour messaging pipeline sends 400,000 transactional emails a month. Every one of them...
Leer más
Como criar um cartão de visita digital interativo com QR Code
Por Muhammad Jahangeer July 08, 2026
Você sai de um evento de networking no centro de São Paulo com 47 cartões de papel na mão. Duas semanas depois, 45 deles estão perdidos em uma...
Leer más