Step 1 of 4Build the list with your own slugs

Create links in bulk from your backend (batch API)

After this guide, your backend creates any number of links in calls of 500, reads every item's result, and can re-run the same job after a crash without making duplicates.

On this page 6
  1. 1. Build the list with your own slugs
  2. 2. Send it in calls of 500, with safe retries
  3. 3. Store the short links next to your data
  4. 4. Fix the items that failed
  5. Common errors
  6. Next steps
Time
About 30 minutes
You need
A secret key (Dashboard → Settings → Keys) in your server's environment as SECRET_KEY, and a list of links to make
Works on
Any server. Code for Node 18+, Python 3.8+ (requests), PHP 8.1+ (ext-curl), Java 17+ and Go 1.21+.

Use the batch endpoint when you make links from data: one per product in a catalogue, per store, per referral partner, or a whole import from another provider. One call to POST /v1/links/batch takes up to 500 links, checks each one exactly like POST /v1/links, and answers with one result per item. For a single link at checkout or signup, call POST /v1/links instead.

1. Build the list with your own slugs

Give every link a slug you can work out again from your own data, like p-42 for product 42 or store-blr-07. Slugs are 1 to 64 letters, digits, _ or -, and unique in your workspace. Because you choose them, running the same job twice can't create a second copy: the second run gets 409 for slugs that already exist.

Each item takes the same fields as a single link. Put UTM tags on the destination so Analytics knows the channel and campaign without extra work:

One item
{
  "slug": "p-42",
  "longUrl": "https://shop.example.com/product/42?utm_source=catalogue&utm_campaign=diwali-2026",
  "title": "Brass diya set",
  "tags": ["catalogue"]
}

You should see: a list where no slug appears twice. A repeat inside one call is a 409 for the later item ("slug repeats item 3 of this batch").

2. Send it in calls of 500, with safe retries

The code below splits the list into calls of 500 and retries a call on a network error, 429 or 5xx. Retrying a whole call is safe: links created by the first try come back as 409 on the second, and the code counts those as done. Any other 4xx stops the job, because sending it again won't help.

Node: batch-links.mjs
// Node 18+ (global fetch). Creates any number of links, 500 per call; safe to re-run.
const API = 'https://strait.link/v1/links/batch';
const CHUNK = 500;

export async function createLinks(links, { secretKey = process.env.SECRET_KEY, fetchImpl = fetch, retryDelayMs = 1000 } = {}) {
  const created = [];
  const existing = [];
  const failed = [];
  for (let start = 0; start < links.length; start += CHUNK) {
    const chunk = links.slice(start, start + CHUNK);
    const data = await postWithRetry({ links: chunk }, secretKey, fetchImpl, retryDelayMs);
    for (const r of data.results) {
      const slug = chunk[r.index].slug;
      if (r.ok) created.push(r.link);
      else if (r.status === 409) existing.push(slug);
      else failed.push({ slug, status: r.status, error: r.error, reason: r.reason });
    }
  }
  return { created, existing, failed };
}

async function postWithRetry(payload, secretKey, fetchImpl, retryDelayMs, attempts = 4) {
  for (let attempt = 1; ; attempt++) {
    let res;
    try {
      res = await fetchImpl(API, {
        method: 'POST',
        headers: { Authorization: `Bearer ${secretKey}`, 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });
    } catch (err) {
      if (attempt >= attempts) throw err;
    }
    if (res?.ok) return res.json();
    if (res && res.status !== 429 && res.status < 500) throw new Error(`batch refused: HTTP ${res.status} ${await res.text()}`);
    if (attempt >= attempts) throw new Error(`batch failed after ${attempts} attempts (HTTP ${res?.status ?? 'network error'})`);
    await new Promise((resolve) => setTimeout(resolve, retryDelayMs * 2 ** (attempt - 1)));
  }
}
Python: batch_links.py
import os
import time

import requests

API = "https://strait.link/v1/links/batch"
CHUNK = 500


def post_with_retry(payload, attempts=4):
    for attempt in range(1, attempts + 1):
        try:
            res = requests.post(
                API,
                headers={"Authorization": f"Bearer {os.environ['SECRET_KEY']}"},
                json=payload,
                timeout=60,
            )
        except requests.RequestException:
            if attempt == attempts:
                raise
        else:
            if res.ok:
                return res.json()
            if res.status_code != 429 and res.status_code < 500:
                raise RuntimeError(f"batch refused: HTTP {res.status_code} {res.text}")
            if attempt == attempts:
                raise RuntimeError(f"batch failed after {attempts} attempts (HTTP {res.status_code})")
        time.sleep(2 ** (attempt - 1))


def create_links(links):
    created, existing, failed = [], [], []
    for start in range(0, len(links), CHUNK):
        chunk = links[start:start + CHUNK]
        for r in post_with_retry({"links": chunk})["results"]:
            slug = chunk[r["index"]]["slug"]
            if r["ok"]:
                created.append(r["link"])
            elif r["status"] == 409:
                existing.append(slug)
            else:
                failed.append({"slug": slug, "status": r["status"], "error": r.get("error"), "reason": r.get("reason")})
    return created, existing, failed
PHP: batch-links.php
<?php
// Plain PHP with ext-curl. In Laravel, run createStraitLinks() from a queued job.

function postStraitBatch(array $payload, int $attempts = 4): array
{
    for ($attempt = 1; ; $attempt++) {
        $ch = curl_init('https://strait.link/v1/links/batch');
        curl_setopt_array($ch, [
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 60,
            CURLOPT_HTTPHEADER => [
                'Authorization: Bearer ' . getenv('SECRET_KEY'),
                'Content-Type: application/json',
            ],
            CURLOPT_POSTFIELDS => json_encode($payload, JSON_THROW_ON_ERROR),
        ]);
        $response = curl_exec($ch);
        $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
        if ($response !== false && $status >= 200 && $status < 300) {
            return json_decode($response, true, 512, JSON_THROW_ON_ERROR);
        }
        if ($response !== false && $status !== 429 && $status < 500) {
            throw new RuntimeException("batch refused: HTTP $status $response");
        }
        if ($attempt >= $attempts) {
            throw new RuntimeException("batch failed after $attempts attempts (HTTP $status)");
        }
        sleep(2 ** ($attempt - 1));
    }
}

function createStraitLinks(array $links): array
{
    $created = $existing = $failed = [];
    foreach (array_chunk($links, 500) as $chunk) {
        foreach (postStraitBatch(['links' => $chunk])['results'] as $r) {
            $slug = $chunk[$r['index']]['slug'];
            if ($r['ok']) {
                $created[] = $r['link'];
            } elseif ($r['status'] === 409) {
                $existing[] = $slug;
            } else {
                $failed[] = ['slug' => $slug, 'status' => $r['status'], 'error' => $r['error'] ?? null];
            }
        }
    }
    return [$created, $existing, $failed];
}
Java: StraitBatch.java
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

// Java 17+. Sends one call of up to 500 links (a JSON body you build with Jackson or Gson)
// and returns the response JSON. Split bigger lists into chunks of 500 and read each
// results[i]: ok, or status 409 (already exists), or another status (fix that item).
public final class StraitBatch {
    private static final HttpClient HTTP = HttpClient.newHttpClient();

    private StraitBatch() {}

    public static String postWithRetry(String linksJson) throws IOException, InterruptedException {
        int attempts = 4;
        for (int attempt = 1; ; attempt++) {
            HttpRequest request = HttpRequest.newBuilder(URI.create("https://strait.link/v1/links/batch"))
                .timeout(Duration.ofSeconds(60))
                .header("Authorization", "Bearer " + System.getenv("SECRET_KEY"))
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString("{\"links\":" + linksJson + "}"))
                .build();
            int status = -1;
            try {
                HttpResponse<String> res = HTTP.send(request, HttpResponse.BodyHandlers.ofString());
                status = res.statusCode();
                if (status >= 200 && status < 300) return res.body();
                if (status != 429 && status < 500) throw new IllegalStateException("batch refused: HTTP " + status + " " + res.body());
            } catch (IOException e) {
                if (attempt >= attempts) throw e;
            }
            if (attempt >= attempts) throw new IllegalStateException("batch failed after " + attempts + " attempts (HTTP " + status + ")");
            Thread.sleep(1000L << (attempt - 1));
        }
    }
}
Go: batch.go
package straitlinks

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
	"time"
)

type Link struct {
	Slug    string   `json:"slug"`
	LongURL string   `json:"longUrl"`
	Title   string   `json:"title,omitempty"`
	Tags    []string `json:"tags,omitempty"`
}

type Result struct {
	Index  int             `json:"index"`
	OK     bool            `json:"ok"`
	Status int             `json:"status"`
	Link   json.RawMessage `json:"link,omitempty"`
	Error  string          `json:"error,omitempty"`
}

// CreateLinks sends links in calls of 500. Results are in input order; status 409 means the slug already exists.
func CreateLinks(links []Link) ([]Result, error) {
	var all []Result
	for start := 0; start < len(links); start += 500 {
		end := min(start+500, len(links))
		results, err := postWithRetry(links[start:end], 4)
		if err != nil {
			return all, err
		}
		for i := range results {
			results[i].Index += start
		}
		all = append(all, results...)
	}
	return all, nil
}

func postWithRetry(chunk []Link, attempts int) ([]Result, error) {
	payload, err := json.Marshal(map[string][]Link{"links": chunk})
	if err != nil {
		return nil, err
	}
	client := &http.Client{Timeout: 60 * time.Second}
	for attempt := 1; ; attempt++ {
		req, err := http.NewRequest(http.MethodPost, "https://strait.link/v1/links/batch", bytes.NewReader(payload))
		if err != nil {
			return nil, err
		}
		req.Header.Set("Authorization", "Bearer "+os.Getenv("SECRET_KEY"))
		req.Header.Set("Content-Type", "application/json")
		status := 0
		res, err := client.Do(req)
		if err == nil {
			body, readErr := io.ReadAll(res.Body)
			res.Body.Close()
			status = res.StatusCode
			if readErr == nil && status >= 200 && status < 300 {
				var out struct {
					Results []Result `json:"results"`
				}
				if err := json.Unmarshal(body, &out); err != nil {
					return nil, err
				}
				return out.Results, nil
			}
			if status != 429 && status < 500 {
				return nil, fmt.Errorf("batch refused: HTTP %d %s", status, body)
			}
		}
		if attempt >= attempts {
			return nil, fmt.Errorf("batch failed after %d attempts (HTTP %d, %v)", attempts, status, err)
		}
		time.Sleep(time.Second << (attempt - 1))
	}
}

You should see: for a first run of 1,200 links, three calls and created holding 1,200 links, each with its shortUrl. Run it again and existing holds 1,200 slugs, with nothing created twice.

Each created item carries shortUrl (like https://hilltop.strait.link/p-42) and id. Save shortUrl on your product, store or partner row, so your emails, WhatsApp messages and invoices read it from your own database instead of calling the API again.

You should see: your table filled with shortUrl values, and the same links in Dashboard → Links when you filter by the tag you set.

4. Fix the items that failed

Read status and error for each item in failed:

status What it means What to do
400 A field is wrong (slug rules, a non-https URL), or error is destination_blocked Fix the item. reason says why a destination was blocked.
402 Your plan's link limit is reached Upgrade, or wait for next month: the limit counts links created this month
409 The slug already exists (counted as existing above) Nothing, if it's your earlier run. To point it somewhere new, update the link.

You should see: an empty failed list after you fix those items and run the job again.

Common errors

  • The whole call gets 400. links is missing, empty or longer than 500. Split the list into calls of 500, as in step 2.
  • The whole call gets 401. The key is missing, or it's a publishable key (st_pub_live_…). Batch needs a secret key (st_live_…), from your server only.
  • Items come back 409 on the very first run. The slugs clash with links someone made in the dashboard, or repeat inside your list. Add a prefix per job, like diwali-p-42.

Next steps