Free URL Shortener APIs

Free API support shortens links with supporting documentation to help you deploy large and automated systems. There are some important information for installing the link shortener API:
  • Url:
  • Method: POST
  • Data: json format

Implementing an external API into your project is probably going to take more than just one API call and from different pages in your project. This is why I’ve created a ‘simple’ PHP script that allows us to call this function, with a set of parameters, and a cURL request will be done.

Make sure to put this code into a file or place that can be accessed by your entire app or website. (I’ve updated this function so we’ll be able to define the headers when we’re making the call. I’ve added a section for custom headers at the bottom!)

function callAPI($method, $url, $data){
   $curl = curl_init();
   curl_setopt($curl, CURLOPT_POST, 1);
   if ($data)
     curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
   // OPTIONS:
   curl_setopt($curl, CURLOPT_URL, $url);
   curl_setopt($curl, CURLOPT_HTTPHEADER, array(
     'Content-Type: application/json',
   curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
   curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
   // EXECUTE:
   $result = curl_exec($curl);
   if(!$result){die("Connection Failure");}
   return $result;

This is a basic setup for doing a cURL call and I’m using a switch statement to check if the API call will be a POST, PUT, or something else (get or delete). I’ll go deeper into the switch case while we’re doing the specific requests.

I’m using if-statements inside the switch-case to see if we want to provide JSON data into our call or not. For the POST and PUT request the if-statement is not really necessary because we’re only using POST or PUT with data, but it’s an extra security to make sure our call function won’t break.

PHP cURL POST request

Obviously, a POST request does require data. Make sure your json-data is correct, otherwise the request will keep returning errors. Although… If we receive errors from the API, that means our calls are working 😉

In my example I’m using the CakePHP syntax for setting up my json array, so don’t mind that.

$data_array = array(
   //Your secret key, when you create your account you will be provided with this code
   "secret_key" => "e10adc3949ba59abbe56e057f20f883e",
   //links you want to shorten
   "url" => '',
$make_call = $this->callAPI('', json_encode($data_array));
$response = json_decode($make_call, true);
   $link= $response['shortened_full'];

Because we’re doing an API call with json data, I’m converting my PHP array to a json string with json_encode($data_array);. The response will come in as a json string again, so I’m using json_decode($make_call, true); to convert the json string back to a usable PHP array. Same as we did in our GET call, so you can skip these steps again if you don’t need them.