javascriptjqueryapiyourls

getting shorturl with yourls api


Is there a way using javascript/jquery to have a short url returned with the yourls API, where if I send a URL, if there is already a shorturl created it just returns the ShortURL if not, it creates a random one and then returns that newly created one?

I've read all the API I can, but it is not indepth enough to figure that out, so I'm wondering if anyone who has done this knows where I can find that specific documentation.

I want to allow people that have a long url to click a link and get a short url returned, which if it already exists, I don't want it created again.

I would appreciate your tips/advice if you have the know how.

Thank you kindly, -Richard


Solution

  • Your question is rather targeted towards the YOURLS backend. I can confirm that if you are using a recent version of YOURLS, on default there will be no duplicate short URLs. If you are submitting a long URL more than once, the API will still return the same short URL (to your Javascript client).

    You can find that setting in the config.php on your YOURLS server:

    /** Allow multiple short URLs for a same long URL
     ** Set to true to have only one pair of shortURL/longURL (default YOURLS behavior)
     ** Set to false to allow multiple short URLs pointing to the same long URL (bit.ly behavior) */
    define( 'YOURLS_UNIQUE_URLS', true );
    

    So be sure that setting is set to true.


    To help get you started, here's an easy way to create short URLs using Javascript. I'm using this third party wrapper for YOURLS.

    You will need to connect to your server with a username/password or alternatively your signature token:

    var api = yourls.connect('http://your.server/yourls-api.php', {
      username: 'admin',
      password: 'qwerty'
    });
    

    If the connection is up, you can use .shorten():

    api.shorten('https://yourverylonglink.com/toshorten', function(data) {
      console.log(data.shorturl); // returns http://your.server/1234
    });