Creating short links from JavaScript application

Another way to create short links is by using a POST HTTP request to https://api.short.io/links/public, with JSON body.

Prerequisites

  1. Create a public API key from the Integrations and API menu: https://app.short.io/settings/integrations/api-key







  1. Create an .html file and include the following code:

📘

Please replace example.xyz and APIKEY with the appropriate values.

<html>
  <head>
    <link>
  </head>
  <body>
    <h1 class="message">Shorten your first link!</h1>
      <div>
          <input name="text" type="url" value  id="linkinput" placeholder="Paste a URL to shorten" >
          <input type="submit" id="myinput" value="Shorten">
      </div>
    <p id="message"></p>
 <script>
document.getElementById("myinput").onclick = function() {
  var link = document.getElementById("linkinput").value;
  var data = {
    "domain":"<<domain_name>>",
    "originalURL": link,
    "allowDuplicates":false }; 
 fetch('https://api.short.cm/links/public', {
    method: 'post',
    headers: {
      'accept': 'application/json',
      'Content-Type': 'application/json',
      'authorization': '<<apiKey>>'
    },
    body: JSON.stringify(data)
  }) .then(function(response) {
        return response.json();
    }) 
    .then(function(data){ 
    document.getElementById("message").innerHTML = "Your short link is " + data.shortURL })
    document.getElementById("linkinput").value='';
 }
    </script>
  </body>
</html>

To create short links using Javascript

Before testing the functionality, it is necessary to host your file on a server/domain. One simple method to demonstrate how the code works is to deploy it to the Cloudflare Pages platform:

  1. From your Cloudflare Dashboard navigate to the Workers and Pages -> Pages tab:

  1. In the Use direct upload section click on Get started.
  2. Enter a name for your project and click on Create project:

  1. Drag or upload the .html file that you created as .zip archive or included in a folder:
  1. After the successful upload click on Deploy site.
  2. A message including the name of your hosted page is displayed:
  1. In your browser's address bar enter the above name followed by /the-name-of-the-html-file, for example: https://shortio-js.pages.dev/short_links_js.html. The following website is displayed:
  1. Paste a URL to shorten in the field and click on Shorten. A message with the newly created short link is displayed below:




You can review the short link from the Short.io Dashboard: