Skip to content

Creating Short Links Through the API with PHP, Python, and JavaScript

Creating Short Links Through the API with PHP, Python, and JavaScript

The previous article explains the basics of Kencang.in API authentication. Now let's look at the code. Below are examples of creating short links in the three languages our users use most: PHP for WordPress and Laravel sites, Python for automation and data scripts, and JavaScript in Node.js for modern services. Every example reads the API key from an environment variable rather than hardcoding it.

Endpoint used

POST https://kencang.in/api/url/add with a JSON body. The minimum parameter is url. A successful response has error: 0, id, and shorturl. A complete list of parameters is in developer documentation.

PHP with cURL

<?php
$key = getenv('KENCANG_KEY');
$payload = json_encode([
    'url'    => 'https://yourstore.com/promo',
    'custom' => 'may-promo',
]);

$ch = curl_init('https://kencang.in/api/url/add');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => $payload,
    CURLOPT_TIMEOUT        => 10,
    CURLOPT_HTTPHEADER     => [
        'Authorization: Bearer ' . $key,
        'Content-Type: application/json',
    ],
]);
$response = curl_exec($ch);
$status   = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);

$data = json_decode($response, true);
if ($status !== 200 || !isset($data['error']) || $data['error'] !== 0) {
    throw new RuntimeException($data['message'] ?? "HTTP $status");
}
echo $data['shorturl'];

In Laravel, you can replace the cURL block with Http::withToken($key)->post(...). In WordPress, use wp_remote_post() to follow the site's proxy and SSL configuration. See the PHP cURL function reference in the official PHP documentation.

Python with requests

Python - Creating Short Links Through the API with PHP, Python, and JavaScript
Python

The requests library handles JSON serialization through the json= parameter and automatically adds the Content-Type header. Always set timeout so the script does not hang if the network has problems. To create hundreds of links from a CSV file, wrap this call in a loop and add a small delay based on your plan's rate limit.

JavaScript (Node.js 18+) with fetch

Node.js - Creating Short Links Through the API with PHP, Python, and JavaScript
Node.js

Node.js 18 and later include fetch built in. Do not run this code in the browser, because anyone opening DevTools would see the API key. If your frontend needs to create links, create an endpoint on your backend that calls the Kencang.in API. Read the fetch documentation on MDN Web Docs.

Handling responses correctly

  • Check the HTTP status code first: 200 means success, 401 an invalid key, 403 a feature unavailable on your plan, 429 a rate limit exceeded, and 5xx a server problem.
  • Then check error in the body. Some validation errors, such as an alias already in use or an invalid URL, return status 200 and error: 1 along with the message.
  • Save id returned in your own database, because you need it to update or delete the link.
  • Make requests idempotent where possible: use a deterministic alias, such as a product code, so repeated calls do not create duplicate links.

A real-world example

An online store adds a hook when a new product is published. The hook calls the API with the product SKU as the alias, then saves shorturl in a product column. The social media team simply copies the link from the admin panel, and every click is recorded per product. The same pattern can create bulk QR codes for packaging.

Next steps

Once link creation is running, add the rate limit and retry handling described in the article API rate limits and error handling, or receive click notifications through webhook.

Frequently asked questions

Why is the response 200 but the link is not created?

Check the error value in the response body. Validation errors such as an alias already in use or an invalid URL return status 200 and an error value of 1 with a message. Your code must check both the HTTP status and the error key.

How can I avoid duplicate links when retrying requests?

Use a deterministic alias, for example product code or order ID. If the first request is actually successful, the repeat will be rejected because the alias already exists, and your application can retrieve the already created link instead of creating a new one.

Is there an official library for PHP or Python?

The Kencang.in API uses standard REST with JSON, so each language's standard HTTP libraries are enough: cURL or Guzzle in PHP, requests in Python, and fetch in Node.js. You can copy the examples in this article straight into your project.

What request timeout is recommended?

Ten seconds is enough under normal conditions. Redirects and link creation usually finish in hundreds of milliseconds, so requests that time out are more likely affected by network problems and should be retried after a delay.

Tim Kencang.in

Ditulis oleh tim produk dan marketing Kencang.in, pemendek link, QR code dinamis, dan bio page buatan Indonesia yang dioperasikan oleh PT Kode Digital Solusindo. Kami menulis berdasarkan pengalaman mengelola kampanye klien dan membangun fitur yang dibahas.

Tentang Kencang.in Contact us